【问题标题】:php domdocument get node infophp domdocument 获取节点信息
【发布时间】:2017-10-21 14:35:53
【问题描述】:

我正在使用 php,我正在尝试从网页获取某些数据

一切正常,直到我到达这部分:

<a class="cleanthis" href="https://www.web.com" id="1122" rel="#1122" style="display: inline-block;"><strong>the data i want</strong></a>

如您所见,我想要强大的数据,但我无法得到它。我只得到空行

我使用的代码:

foreach($as as $a) {
        if ($a->getAttribute('class') === 'cleanthis') {


$strong =  $a->getElementsByTagName('strong');
echo $strong->nodeValue;;

}

【问题讨论】:

  • 可能是因为简化而打错了,但是类是cleanthis,而你正在寻找hoverinfo_trigger
  • 我打错字了,抱歉
  • 我会使用该样式来使文本更强大.. 不赞成与标记混合的样式。然后您可以通过 ID 选择元素,例如..
  • 我无法更改,这是来自其他网站,所以我无能为力。

标签: php domdocument


【解决方案1】:

您应该会看到以下错误消息:

未定义属性:DOMNodeList::$nodeValue

那是因为$strong = $a-&gt;getElementsByTagName('strong'); 会将DOMNodeList 放入$string。您需要迭代列表或从中检索实际节点,例如

echo $strong->item(0)->nodeValue;

或者您可以只使用 XPath:

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
foreach ($xpath->evaluate('//a[@class="cleanthis"]/strong/text()') as $element) {
    echo $element->nodeValue, PHP_EOL;
}

【讨论】:

  • 我必须使用 domdocument 的方式,还是不行
猜你喜欢
  • 1970-01-01
  • 2018-08-02
  • 2015-09-28
  • 2023-04-02
  • 2012-10-22
  • 1970-01-01
  • 2011-10-13
  • 2013-05-14
  • 1970-01-01
相关资源
最近更新 更多