【发布时间】: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->query('div[@class="firstlevel other class too"]'开始查询或在 xpath$node = $xpath->query('//div[@class="firstlevel other class too"]'中添加双斜杠。在循环之外执行此操作,因为您将完整的 xpath 传递给元素,在这种情况下无需迭代元素。
标签: php xpath domdocument