如何使用Simple HTML Dom Parser抓取Bing图像?

问题描述 投票:1回答:1

我正在构建一个PHP搜索引擎。 我想要有不同的搜索类型。像用户可以搜索图像,网站,视频等。 现在我正在尝试两件事: 1:仅搜索视频。 2:仅搜索图像。 我正在爬网,使用Bing。像这样:

$bing = 'https://www.bing.com/images/search?q='. rawurlencode($keyword);

我正在使用Simple HTML Dom Parser来获取所有结果。 我从浏览器的Inspect Element控制台知道Bing中图像的整个“路径”是这样的:

$img = $html->find('div[data-bm] div[class=dg_b] div[class=dgControl]ul[class=dgControl_list] li div[class=varh] div[class=imgpt] a[class=iusc] div[class=hoff] img[class=mimg]');

但如果我这样做:

if($img) {
 // rest of the code ...                    
}
else {
    echo 'false';
}

我弄错了,因为我插入的搜索路径不正确。 但我确信它确实存在。 完全相同的问题是视频搜索。 我搜索了整个互联网,但我没有找到任何解决方案。 有人知道解决方案吗? 亲切的问候,

编辑 我忘了提到以下内容: 如果我只是一个图像作为查找路径像:$img = $html->find('img');,我得到结果。 但问题是,如果我这样做,我得到的结果根本不相关。 就像我搜索特朗普一样,我得到一张海滩照片和一些西红柿照片,我认为这完全是荒谬的。 编辑2 我发现$ html-> load_file()不起作用。 我通过运行这个来测试它:

if(!$html->load_file($bing)) {
     echo 'load file doesn't work....';
}

可能是因为我有多次$ html = ...像这样:

if($_GET['type'] == 'default') { // rest of the code }
else if($_GET['type'] == 'vids') { // rest of the code }
else if($_GET['type'] == 'images') { // rest of the code }
else if($_GET['type'] == 'news') { // rest of the code }

在每个else-if语句中,它以$html = simple_html_dom();开头 但它也以$html->clear(); unset($html);结束 但如果我测试$html->clear(); unset($html);是否像这样工作:

if($html->clear()) {
     unset($html);                    
     echo 'clear worked!';
}
else {
     echo 'clear didn't work :(';
}

我明白了:清除不起作用:( 所以这意味着$html->load_file();$html->clear();有问题

php web-crawler simple-html-dom
1个回答
0
投票

我发现使用DOMDocument和XPath要容易得多,所以这显示了我如何管理上述内容。

我倾向于接近它的方法是在PHP中加载页面然后将其保存到文件中,然后将文件用于路径,因为这有时与浏览器路径不同。使用此保存的文件将引导我进入以下XPath。

使用的XPath是//span[@id="main"]//a[@class="thumb"]//img/@src,它应该相当容易遵循(带有id属性为main的span标签,然后是带有拇指类的a标签,并查找其中的图像标签,最后返回src属性)...

$content = file_get_contents("https://www.bing.com/images/search?q=cat");
file_put_contents("b.html", $content);

$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($content);

$xp = new DOMXPath($dom);

$images = $xp->query('//span[@id="main"]//a[@class="thumb"]//img/@src');

foreach ( $images as $image )   {
    echo $image->nodeValue.PHP_EOL;
}
© www.soinside.com 2019 - 2024. All rights reserved.