首页 > 解决方案 > 使用 XPath 访问子段落内容

问题描述

HTML:

<div class="b-list-fact__item-explanation js-fact-explanation">
    <p>Text 1 Text 1 Text 1 Text 1 Text 1 Text 1</p>
    <p>Text 2 Text 2 Text 2 Text 2 Text 2 Text 2 </p>
</div>

我正在尝试访问段落内的文本并将所有p' 组合成一个字符串。

正在尝试一系列变化,例如:

PHP(在 7.1.11 上运行):

    $html = file_get_contents('https://...');
    $html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
    $dom = new DOMDocument;
    @$dom->loadHTML($html);

    $finder = new DomXPath($dom);
    $facts = $finder->query("//a[contains(@class, normalize-space('b-list-fact__item-text'))]");
    $long_fact = $finder->query("//*[contains(@class, 'b-list-fact__item-explanation js-fact-explanation')]/p");

    foreach ($facts as $key => $fact) {
            $fact_description = $long_fact[$key]->textContent;
            $fact = trim($fact->textContent);
            $dataArr[] = str_replace("\n", " ", $fact);
            array_push($dataArr, $fact_description);
    }

$long_fact = $finder->query("//*[contains(@class, 'b-list-fact__item-explanation js-fact-explanation')]/p");

$long_fact = $finder->query("//*[contains(@class, 'b-list-fact__item-explanation js-fact-explanation')]//p[1]");

$long_fact = $finder->query("//*[contains(@class, 'b-list-fact__item-explanation js-fact-explanation')]/p/text()");

if($long_fact->length)
        {
            var_dump($long_fact[0]->textContent);
        }

if($$long_fact->length)
        {
            var_dump($long_fact->textContent);
        }

if($$long_fact->length)
        {
            var_dump($long_fact->nodeValue);
        }

和其他 30 种变体一样...

我完全不知道为什么会发生这种情况,其他不包含p标签的变体工作得很好。

标签: phpxpath

解决方案


$ptext = $finder->query('//div[contains(@class, "b-list-fact__item-explanation js-fact-explanation")]/p');
$paragraphs = [];
foreach ($ptext as $paragraph) {
    $paragraphs[] = $paragraph->textContent;
}
$combined = implode("\n", $paragraphs);

或者只是:

$ptext = $finder->query('//div[contains(@class, "b-list-fact__item-explanation js-fact-explanation")]')
    ->item(0)->textContent;

推荐阅读