19

使用 PHP Xpath 尝试快速拉取 html 页面中的某些链接。

以下将在 mypage.html 上找到所有 href 链接: $nodes = $x->query("//a[@href]");

而以下将找到描述与我的针相匹配的所有href链接: $nodes = $x->query("//a[contains(@href,'click me')]");

我想要实现的是匹配 href 本身,更具体地查找包含某些参数的 url。这在 Xpath 查询中是否可行,还是我应该开始处理第一个 Xpath 查询的输出?

4

1 回答 1

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')]");

输出:

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"
    }
  }
}

但是您现在可以通过以下方式输出 URL

echo $list[0] // gives "http://example.com/page?foo=bar"
于 2010-03-06T12:29:03.583 回答