代码之家  ›  专栏  ›  技术社区  ›  Ricardo

使用XPath访问子段落内容

  •  0
  • Ricardo  · 技术社区  · 7 年前

    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 标签工作正常。

    1 回复  |  直到 7 年前
        1
  •  1
  •   rob006    7 年前
    $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;