【问题标题】:Symfony Dom Crawler Missing Node, Inconsistent BehaviourSymfony Dom Crawler 缺少节点,行为不一致
【发布时间】:2019-04-06 04:37:03
【问题描述】:

使用此代码:

use Symfony\Component\DomCrawler\Crawler;
require_once(__DIR__ . '/../vendor/autoload.php');

$html = <<<'HTML'
<!DOCTYPE html>

<html>
    <body>
        <p class="message">Hello World!</p>
        <p>Hello Crawler!</p>
        <p>OUTSIDE
            <span>
                Child SPAN
            </span>
            <div>
                Child DIV
            </div>
            <p>
                Child PARAGRAPH
            </p>
        </p>
    </body>
</html>

HTML;

$crawler = new Crawler($html);
$crawlerFiltered = $crawler->filter('body > p');

$results = [];
$childResults = [];
for ($i=0; $i<count($crawlerFiltered); $i++) {
    $results[] = $crawlerFiltered->eq($i)->html();

    $children = $crawlerFiltered->eq($i)->children();
    if (count($children)) {
        for ($j=0; $j<count($children); $j++) {
            $childResults[] = $children->eq($j)->html();
        }
    }
}

echo 'Parent Nodes:' . PHP_EOL;
var_export($results);
echo PHP_EOL;
echo 'Child Nodes:' . PHP_EOL;
var_export($childResults);

我得到结果:

Parent Nodes:
array (
  0 => 'Hello World!',
  1 => 'Hello Crawler!',
  2 => 'OUTSIDE
            <span>
                Child SPAN
            </span>
            ',
  3 => '
                Child PARAGRAPH
            ',
)
Child Nodes:
array (
  0 => '
                Child SPAN
            ',
)

这代表以下问题:

  1. 子结果:没有 DIV 或 P(只有内联标签)
  2. 父结果:PHARAGRAPH 无标签,与 SPAN 不一致
  3. 父结果:应该只包含第一个 p 因为第二个 p (PHARAGRAPH) 不 有 body 作为父母但 p

您知道这是为什么以及如何解决上述问题吗?

【问题讨论】:

    标签: php symfony css-selectors components domcrawler


    【解决方案1】:

    The documentation for this component 状态:

    注意

    DomCrawler 将尝试自动修复您的 HTML 以匹配官方规范。例如,如果您将&lt;p&gt; 标记嵌套在另一个&lt;p&gt; 标记中,它将被移动为父标记的兄弟。这是预期的,是 HTML5 规范的一部分。

    使用内置的DomDocument 类可能会更好。大多数 HTML 解析器旨在处理 "tag soup",并会尝试纠正感知到的问题。

    【讨论】:

    • 确实,尽管这个问题的标题暗示了什么,但这实际上是为了与浏览器的一致性,如果它与浏览器行为不匹配,它将是“不一致的”。
    猜你喜欢
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2012-10-18
    相关资源
    最近更新 更多