Vytas P.
Vytas P.

Reputation: 983

xpath expression to select text from link

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.

Upvotes: 10

Views: 23022

Answers (3)

Tomalak
Tomalak

Reputation: 338208

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.

Upvotes: 3

pablochan
pablochan

Reputation: 5715

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

Upvotes: 17

Frank
Frank

Reputation: 10571

It depends also on the rest of your document. If you use // in the beginning all the matching nodes will be returned, which might be too many results in case you have other links in your document.

Apart from that a possible xpath expression is //a/text().

The /a you tried only returns the a-tag itself, if it is the root element. To get the link text you need to append the /text() part.

Upvotes: 3

Related Questions