Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath expression to select text from link

Tags:

xpath

I have such content of html file:

<a class="bf" title="Link to book" href="/book/229920/">book name</a>

Help me to construct xpath expression to get link text (book name). I try to use /a, but expression evaluates without results.

like image 586
Vytas P. Avatar asked Feb 22 '10 14:02

Vytas P.


People also ask

How do I find the XPath of a link?

Launch the Chrome browser and navigate to the URL or webpage. Hover the mouse over the desired element (object) on the web page, right-click on the element you are looking for XPath, and select “Inspect.”

What is text () function in XPath?

XPath text() function is a built-in function of the Selenium web driver that locates items based on their text. It aids in the identification of certain text elements as well as the location of those components within a set of text nodes. The elements that need to be found should be in string format.

How do I find the XPath of text?

So, inorder to find the Text all you need to do is: driver. findElement(By. xpath("//*[contains(text(),'the text you are searching for')]"));


2 Answers

Have you tried

//a

?

More specific is better:

//a[@class='bf' and starts-with(@href, '/book/')]

Note that this selects the <a> element. In your host environment it's easy to extract the text value of that node via standard DOM methods (like the .textContent property).

To select the actual text node, see the other answers in this thread.

like image 62
Tomalak Avatar answered Nov 09 '22 00:11

Tomalak


If the context is the entire document you should probably use // instead of /. Also you may (not sure about that) need to get down one more level to retrieve the text.

I think it should look like this

//a/text()

EDIT: As Tomalak pointed out it's text() not text

like image 23
pablochan Avatar answered Nov 09 '22 01:11

pablochan