href attribute for lxml.html

nazmus saif picture nazmus saif · Dec 7, 2014 · Viewed 8.8k times · Source

according to this answer:

>>> from lxml.html import fromstring
>>> s = """<input type="hidden" name="question" value="1234">"""
>>> doc = fromstring(s)
>>> doc.value
'1234'
>>> doc.name
'question'

I tried to get both the link and the text from this code:

from lxml.html import fromstring
s = '<a href="http://a.com" rel="bookmark">bla bla bla</a>'
doc = fromstring(s)
print (doc.href)
print (doc.text_content())

It gives a AttributeError:'HtmlElement' object has no attribute 'href'

Im new in lxml. Actually what was the problem?

How can i have both the link (a.com) and the text (bla bla bla) as strings from this code?

Answer

Valeriy Gaydar picture Valeriy Gaydar · Dec 8, 2014

This code works for me

from lxml.html import document_fromstring
doc = document_fromstring('<a href="http://a.com" rel="bookmark">bla bla bla</a>')
print (doc.xpath("//a")[0].get("href"))
print (doc.text_content())

Output:

http://a.com
bla bla bla