使用 PHP Xpath 尝试快速提取 html 页面中的某些链接。
以下将找到 mypage.html 上的所有 href 链接:
$nodes = $x->query("//a[@href]");
而以下将找到所有描述与我的针相匹配的 href 链接:
$nodes = $x->query("//a[contains(@href,'click me')]");
我想要实现的是匹配 href 本身,更具体地查找包含某些参数的 url。这在 Xpath 查询中是否可行,还是我应该开始处理第一个 Xpath 查询的输出?
最佳答案
不确定我是否正确理解了这个问题,但第二个 XPath 表达式已经完成了您所描述的操作。它不匹配A元素的文本节点,而是href属性:
$html = <<< HTML
<ul>
<li>
<a href="http://example.com/page?foo=bar">Description</a>
</li>
<li>
<a href="http://example.com/page?lang=de">Description</a>
</li>
</ul>
HTML;
$xml = simplexml_load_string($html);
$list = $xml->xpath("//a[contains(@href,'foo')]");
输出:
array(1) {
[0]=>
object(SimpleXMLElement)#2 (2) {
["@attributes"]=>
array(1) {
["href"]=>
string(31) "http://example.com/page?foo=bar"
}
[0]=>
string(11) "Description"
}
}
如您所见,返回的 NodeList 仅包含带有 href 的 A 元素,其中包含 foo(我知道这就是您要查找的内容)。它包含整个元素,因为 XPath 转换为获取所有具有包含 foo 的 href 属性的 A 元素。然后,您将使用
访问该属性echo $list[0]['href'] // gives "http://example.com/page?foo=bar"
如果你只想返回属性本身,你必须这样做
//a[contains(@href,'foo')]/@href
请注意,在 SimpleXml 中,这将返回一个 SimpleXml 元素:
array(1) {
[0]=>
object(SimpleXMLElement)#3 (1) {
["@attributes"]=>
array(1) {
["href"]=>
string(31) "http://example.com/page?foo=bar"
}
}
}
但您现在可以通过
输出网址echo $list[0] // gives "http://example.com/page?foo=bar"
关于PHP Xpath : get all href values that contain needle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2392393/