5

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.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
user3196332
  • 361
  • 2
  • 4
  • 11

2 Answers2

6

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
James Mills
  • 18,669
  • 3
  • 49
  • 62
1

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()')
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441