book...">

Xpath expression to select text from link

I have html file content like this:

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

Help me build xpath expression to get link text (book title). I am trying to use /a

but the expression is evaluating with no results.

+6


source to share


3 answers


You tried

//a

      

?

More specific is better:



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

      

Note that this selects the item <a>

. In a host environment, it is easy to extract the text value of that node using standard DOM methods (like a property .textContent

).

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

+2


source


If the context is the entire document, you should probably use //

instead /

. Alternatively, you can (not sure about this) to get one more level to get the text.

I think it should look like this.



//a/text()

      

EDIT: As Tomalak pointed out, text()

nottext

+12


source


It also depends on the rest of your document. If you use //

in the beginning, all matching nodes will be returned, which can be too large if you have other links in your document.

Also, the possible xpath expression is //a/text()

.

The tag /a

you tried only returns a

-tag if it's the root element. To get the link text you need to add a part /text()

.

+3


source







All Articles