Value attribute for lxml.html

Here is my code:

from lxml.html import fromstring
#code
print fromstring(s).xpath('/html/body/div[3]/div/div[2]/div/form/input[4]')

Conclusion [<InputElement 2946d20 name='question' type='hidden'>]

How can I infer the value? Any attribute for this? Thank.

+4
source share
2 answers

In the general case of lxml, you can access the value of an element directly through the attribute .value:

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

In your case, you will also need to access the first element of the resulting list from the XPath query :

print fromstring(s).xpath('/html/body/div[3]/div/div[2]/div/form/input[4]')[0].value
+5
source

This can be done directly from XPath - no need to change the surrounding Python.

print fromstring(s).xpath('/html/body/div[3]/div/div[2]/div/form/input[4]/text()')
+1
source

Source: https://habr.com/ru/post/1532240/


All Articles