【发布时间】:2018-06-30 04:33:00
【问题描述】:
我曾经使用jsoup在Java中解析html。它可以选择和解析几乎所有内容。我最近切换到 PHP 并尝试了几个 DOM 解析器,但 css 选择器没有按预期工作(或者,与 jsoup 一样好)。例如,我尝试使用以下命令选择Google 主页的关于(在左上角)链接:
1。 DOMCrawler - Symfony:
$crawler->filter('#hptl > a:nth-child(1)')->each(function ($node) {
print $node->text()."\n";
});
Result: Empty Page
2。简单的 HTML DOM:
require "simple_html_dom.php";
// Create DOM from URL or file
$html = file_get_html("https://google.com");
// Find innertext of about
foreach($html->find("#hptl > a:nth-child(1)") as $element) {
echo $element->innertext . "<br>";
}
Result: Empty Page
3。 php查询:
$doc = phpQuery::newDocumentFile('https://google.com');
dd($doc->find("#hptl > a:nth-child(1)")->text());
Result: Empty String
但如果我尝试使用jsoup选择元素,jsoup的css选择器可以轻松选择元素。
我用不同的选择器进行了测试,在大多数情况下,他们未能选择我想要的元素,但 jsoup 没有。以下是此类选择器的示例:
div.schedule_table:nth-child(8) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(2) > p:nth-child(1)
我通常从开发工具中复制 css 选择器。我在这个过程中做错了吗?如果没有,是否有更好的解析器对 PHP 具有完整的 css 选择器支持?
【问题讨论】:
-
可以显示输出的html吗?
-
@fauverism 当然。但是哪一个?
-
您是否调试了输出,只是为了确定?开发工具也没有为我找到
#hptl > a:nth-child(1)。可能是一些可变元素。 -
@DonaldDuck 也许只有在用户登录时才会出现 About 页面,这就是我们无法选择它的原因。但即使我打开一个私有窗口并尝试选择另一个可全局访问的元素,例如“Gmail”锚标记,像 Simple HTML Dom 这样的解析器也无法选择它。您能否确认您可以在 google.com 上找到此元素:
div.gb_Q:nth-child(1) > a:nth-child(1)? -
我去了这个网站,复制了页脚的css选择器(
.footer--copyright > span:nth-child(1)):itstillworks.com。我试图用简单的 html dom 选择它,它找不到。然后我去try.jsoup.org,获取url,用相同的选择器搜索相同的元素,找到了。
标签: php css css-selectors html-parsing