XPath Query: get attribute href from a tag

后端 未结 2 1934
忘了有多久
忘了有多久 2020-12-08 04:14

I want to use XPath to get the href attribute from an a-tag, but it has two occurrences within the same file. How am I getting along? I need to che

2条回答
  •  攒了一身酷
    2020-12-08 04:33

    For the following HTML document:

    
      
        Example 
        SO 
      
    
    

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

        http://www.example.com
        http://www.stackoverflow.com
    

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

        $ /html/body//a[2]/@href
        http://www.stackoverflow.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.stackoverflow.com
    

提交回复
热议问题