首页 > 解决方案 > 在简单的 html dom 中按类和 id 选择在谷歌搜索中不起作用

问题描述

我尝试按查找 div 的以下代码不适用于谷歌搜索结果,我也尝试过id

include('simple_html_dom.php');

$dom = file_get_html("https://www.google.com/search?q=best+mug");

$all_divs = $dom->find("div[class='g']");

foreach ($all_divs as $div) {
    echo $div->plaintext;
}

标签: phpregexweb-scrapingsimple-html-dom

解决方案


我认为最好使用 XPath 来做到这一点,下面是使用 XPath 的代码示例:

$dom = file_get_contents("https://www.google.com/search?q=best+mug");
@$doc = new DOMDocument();
@$doc->loadHTML($dom);   

$xpath = new DomXPath($doc);

$all_divs = $xpath->query("//div[@class='g']");

foreach ($all_divs as $div) {
    echo $div->plaintext;
}

试试看,让我知道它是否有效。


推荐阅读