【发布时间】:2020-03-31 07:54:49
【问题描述】:
我目前正在从网络扩展中动态抓取网页,并且正在使用以下代码:
let url = "https://lykdat.com/search-result/?image_url=https://anf.scene7.com/is/image/anf/KIC_330-2455-0904-476_prod1?$product-hol-v1$&wid=800&hei=1000";
fetch(url,{redirect: 'follow'}).then(r => r.text()).then(result => {
console.log(result);
var el = document.createElement( 'html' );
el.innerHTML = result;
// console.log(typeof(tempPage));
console.log(el);
tempImgs = el.getElementsByTagName('img');
console.log(tempImgs);
})
我希望能够更改“image_url=”之后的任何文本,以更改插入网站的图像。不幸的是,我试图从中提取信息的页面是在短暂的加载期之后出现的,因此使用“获取”功能只会从加载屏幕中提取信息,而不是我想要的实际页面。重定向不是即时的,可能需要 3-30 秒之间的任何时间,我想知道是否有任何方法可以强制 fetch 在抓取数据之前等待该重定向。非常感谢您提供的任何帮助报价!
【问题讨论】:
-
虽然,我自己并不了解 JavaScript,但我会使用 PHP 的 DOMDocument。查看 loadHTMLFile,例如
$dom = new DOMDocument; $dom->loadHTMLFile($urlHere); $imgs = $dom->getElementsByTagName('img'); foreach($imgs as $img){ $src = $img->getAttribute('src'); /* $src is src attribute of each image in loop */ }. -
该页面正在使用脚本重定向到最终结果,因此无论您等待多长时间,它们都不会出现在初始 HTML 响应中 - 这是因为
fetch不运行脚本.您需要将该站点嵌入到 iframe 中,使用"all_frames":true和匹配的 URL 模式声明内容脚本,以便它将在该 iframe 中运行,然后通过消息传递 (example) 将结果传达回。
标签: javascript google-chrome-extension fetch