【问题标题】:CSS Selectors for parsing HTML in PHP用于在 PHP 中解析 HTML 的 CSS 选择器
【发布时间】: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 &gt; a:nth-child(1)。可能是一些可变元素。
  • @DonaldDuck 也许只有在用户登录时才会出现 About 页面,这就是我们无法选择它的原因。但即使我打开一个私有窗口并尝试选择另一个可全局访问的元素,例如“Gmail”锚标记,像 Simple HTML Dom 这样的解析器也无法选择它。您能否确认您可以在 google.com 上找到此元素:div.gb_Q:nth-child(1) &gt; a:nth-child(1)
  • 我去了这个网站,复制了页脚的css选择器(.footer--copyright &gt; span:nth-child(1)):itstillworks.com。我试图用简单的 html dom 选择它,它找不到。然后我去try.jsoup.org,获取url,用相同的选择器搜索相同的元素,找到了。

标签: php css css-selectors html-parsing


【解决方案1】:

自 OP 发布以来,Google 登录页面似乎发生了一些变化。尽管如此,我在使用QueryPath 进行类似查询时取得了很好的成功。例如:

<?php
require "vendor/autoload.php";
$qp =html5qp('https://google.com','#footer > div > div > a:nth-of-type(3)');
print_r($qp->text());

返回“关于 Google”

请注意,Google 着陆页的内容取决于 user-agent 请求标头。如果您想匹配您在浏览器中看到的页面,则必须单独下载该页面,并带有适当的 user-agent 请求标头。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 2016-04-07
    • 2018-08-19
    • 2011-02-25
    • 2014-04-29
    • 1970-01-01
    • 2013-02-17
    相关资源
    最近更新 更多