【问题标题】:Using domxpath to parse a some complex nested html使用 domxpath 解析一些复杂的嵌套 html
【发布时间】:2018-04-30 17:04:01
【问题描述】:

我在弄清楚如何从比我在网上找到的任何示例都复杂得多的 html 页面中获取某些文本元素时遇到问题。

我要解析的网站是一个房地产网站,在 html 中它们包含价格和属性状态等内容。如果我们以房产的状态为例,我试图从以下 html 的 sn-p 中获取“待售”:

<div class="repeating container of property details">
<div class="firstlevel other class too">
    <div class="secondlevel other class too">
        <div class="thirdlevel">
            <div class="fourthlevel">
                <span class="thisspan">For Sale</span>
                <span class="someotherspan">Something else</span>
            </div>
        </div>
    </div>
</div>

然后我尝试使用以下 php 提取我需要的内容。

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXpath($doc);

$properties = $xpath->query('//div[@class="repeating container of property details"]');

foreach($properties as $container) {

    $node = $xpath->query('div[@class="firstlevel other class too"]'
        . '/div[@class="secondlevel other class too"]'
        . '/div[@class="thirdlevel"]'
        . '/div[@class="fourthlevel"]'
        . '/span[@class="thisspan"]', $container); // returns a DOMNodeList  
    $result = $node->item(0)->value; // get the first node in the list which is a DOMAttr
    echo 'value: '.$result.'<br/>';
}

但我收到以下错误:

Undefined property: DOMElement::$value

它显然没有选择我想要掌握的内容,到目前为止我尝试过的其他任何方法似乎都不起作用。谁能指出我正确的方向?

【问题讨论】:

  • 尝试从 $properties $node = $properties-&gt;query('div[@class="firstlevel other class too"]' 开始查询或在 xpath $node = $xpath-&gt;query('//div[@class="firstlevel other class too"]' 中添加双斜杠。在循环之外执行此操作,因为您将完整的 xpath 传递给元素,在这种情况下无需迭代元素。

标签: php xpath domdocument


【解决方案1】:

您正在获取元素节点(span),而不是属性节点。元素节点没有$value 属性。使用$textContent 属性:

$result = $node->item(0)->textContent;

或者您将节点列表转换为 Xpath 表达式中的字符串:

$result = $xpath->evaluate('string(div[@class="firstlevel other class too"]'
    . '/div[@class="secondlevel other class too"]'
    . '/div[@class="thirdlevel"]'
    . '/div[@class="fourthlevel"]'
    . '/span[@class="thisspan"])', $container); // returns a DOMNodeList  
echo 'value: '.$result.'<br/>';

这仅适用于DOMXpath::evaluate()DOMXpath::query() 仅支持返回节点列表的表达式。

【讨论】:

    猜你喜欢
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2021-03-17
    • 2021-01-25
    • 2012-10-01
    • 1970-01-01
    相关资源
    最近更新 更多