Nikol
Nikol

Reputation: 187

XPath - get attribute "href"

how can I get the "href" attribute from html using XPath?

<td>
    <a href="http://www.stackoverflow.com">
       <p>SERVER-45472</p>
    </a>
</td>

Why for me works only this command of "//a/@href" ? Why can't I use this query - "/td//a/@href"?

What am I trying to do:

from lxml import html

tree = html.fromstring('<td><a href="https://jira.mongodb.org/browse/SERVER-45472"><p>SERVER-45472</p></a></td>')

a = tree.xpath('/td//a/@href')
print(a)

After running the script, an empty list is returned to me

Upvotes: 1

Views: 328

Answers (2)

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185073

Because a part of a HTML file is not a valid HTML document.

See:

$ python
Python 2.7.16 (default, Oct 10 2019, 22:02:15) 
[GCC 8.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from lxml import html
>>> tree = html.fromstring('<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"><html>  <body><td><a href="https://jira.mongodb.org/browse/SERVER-45472"><p>SERVER-45472</p></a></td></body></html>')
>>> a = tree.xpath('/html/body/td//a/@href')
>>> print(a)
['https://jira.mongodb.org/browse/SERVER-45472']
>>> 

Upvotes: 1

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185073

Like this XPath :

string(//a/@href)
http://www.stackoverflow.com

Your XPath partially works for me with :

xmllint --xpath '/td//a/@href' file
href="http://www.stackoverflow.com"

Which tools are you using, and what is your expected output, and what you get instead ?

Upvotes: 1

Related Questions