How can I find the link URL by link text with XPath?

百般思念 提交于 2019-12-17 15:10:06

问题


I have a well formed XHTML page. I want to find the destination URL of a link when I have the text that is linked.

Example

<a href="http://stackoverflow.com">programming questions site</a>
<a href="http://cnn.com">news</a>

I want an XPath expression such that if given programming questions site it will give http://stackoverflow.com and if I give it news it will give http://cnn.com.


回答1:


Should be something similar to:

//a[text()='text_i_want_to_find']/@href



回答2:


Too late for you, but for anyone else with the same question...

//a[contains(text(), 'programming')]/@href

Of course, 'programming' can be any text fragment.




回答3:


//a[text()='programming quesions site']/@href 

which basically identifies an anchor node <a> that has the text you want, and extracts the href attribute.




回答4:


Think of the phrase in the square brackets as a WHERE clause in SQL.

So this query says, "select the "href" attribute (@) of an "a" tag that appears anywhere (//), but only where (the bracketed phrase) the textual contents of the "a" tag is equal to 'programming questions site'".




回答5:


For case insensitive contains, use the following:

//a[contains(translate(text(),'PROGRAMMING','programming'), 'programming')]/@href

translate converts capital letters in PROGRAMMING to lower case programming.




回答6:


if you are using html agility pack use getattributeValue:

$doc2.DocumentNode.SelectNodes("//div[@class='className']/div[@class='InternalClass']/a[@class='InternalClass']").GetAttributeValue("href","")


来源:https://stackoverflow.com/questions/915338/how-can-i-find-the-link-url-by-link-text-with-xpath

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!