How to find link URL by link using XPath?

I have a well-formed XHTML page. I want to find the destination URL of the link when I have the associated text.

Example

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

I want an XPath expression that, if asked by the programming questions site , will give http://stackoverflow.com , and if I give it news it will give http://cnn.com .

+72
xml xhtml xpath
May 27 '09 at 12:05
source share
6 answers

There should be something similar to:

 // a [text () = 'text_i_want_to_find'] / @ href
+120
May 27, '09 at 12:08
source share

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

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

Of course, โ€œprogrammingโ€ can be any piece of text.

+60
May 23 '11 at 20:00
source share
 //a[text()='programming quesions site']/@href 

which basically identifies the anchor node <a> , which has the desired text, and retrieves the href attribute.

+8
May 27 '09 at 12:10
source share

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

So this query says: "select the" href "(@) attribute of the" a "tag that appears anywhere (//), but only where (the phrase in brackets) the text content of the" a "tag is equal to the" programming questions site " "

+6
May 27 '09 at 14:50
source share

If case insensitive, use the following:

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

translate converts uppercase letters to PROGRAM for lower case programming.

+3
Jan 03 '13 at 21:42
source share

if you use html agility pack use getattributeValue:

 $doc2.DocumentNode.SelectNodes("//div[@class='className']/div[@class='InternalClass']/a[@class='InternalClass']").GetAttributeValue("href","") 
+1
Oct 13 '12 at 22:13
source share



All Articles