使用PHP Xpath尝试快速拉取html页面中的某些链接.
以下内容将在mypage.html上找到所有href链接:
$nodes = $x->query("//a[@href]");
以下将找到描述与我的针匹配的所有href链接:
$nodes = $x->query("//a[contains(@href,'click me')]");
我想要实现的是匹配href本身,更具体的发现包含某些参数的url.这可能在Xpath查询中,还是我应该开始操作第一个Xpath查询的输出?
Gor*_*don 39
我不确定我是否正确理解了这个问题,但是第二个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')]");
Run Code Online (Sandbox Code Playgroud)
输出:
array(1) {
[0]=>
object(SimpleXMLElement)#2 (2) {
["@attributes"]=>
array(1) {
["href"]=>
string(31) "http://example.com/page?foo=bar"
}
[0]=>
string(11) "Description"
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,返回的NodeList仅包含href包含foo的A元素(我理解您正在寻找的内容).它包含整个元素,因为XPath转换为使用包含foo的href属性获取所有A元素.然后,您将使用
echo $list[0]['href'] // gives "http://example.com/page?foo=bar"
Run Code Online (Sandbox Code Playgroud)
如果您只想返回属性本身,则必须这样做
//a[contains(@href,'foo')]/@href
Run Code Online (Sandbox Code Playgroud)
请注意,在SimpleXml中,这将返回一个SimpleXml元素:
array(1) {
[0]=>
object(SimpleXMLElement)#3 (1) {
["@attributes"]=>
array(1) {
["href"]=>
string(31) "http://example.com/page?foo=bar"
}
}
}
Run Code Online (Sandbox Code Playgroud)
但您现在可以输出URL
echo $list[0] // gives "http://example.com/page?foo=bar"
Run Code Online (Sandbox Code Playgroud)