且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

XPath查询:从标签获取属性href

更新时间:2022-06-13 00:03:00

对于以下HTML文档:

For the following HTML document:

<html>
  <body>
    <a href="http://www.example.com">Example</a> 
    <a href="http://www.***.com">SO</a> 
  </body>
</html>

xpath查询 / html / body // a / @ href (或简单地 // a / @ href )将返回:

The xpath query /html/body//a/@href (or simply //a/@href) will return:


    http://www.example.com
    http://www.***.com

选择一个特定的实例使用 / html / body // a [N] / @ href

To select a specific instance use /html/body//a[N]/@href,


    $ /html/body//a[2]/@href
    http://www.***.com

要测试属性中包含的字符串并返回属性本身,请将标记上的检查放在属性上:

To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:


    $ /html/body//a[contains(@href,'example')]/@href
    http://www.example.com

混合两者:

Mixing the two:


    $ /html/body//a[contains(@href,'com')][2]/@href
    http://www.***.com