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.
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
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()')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With