Question

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]')

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

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

Was it helpful?

Solution

In general with lxml you can access an element's value directly via the .value attribute:

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

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

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

OTHER TIPS

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

print fromstring(s).xpath('/html/body/div[3]/div/div[2]/div/form/input[4]/text()')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top