Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

value attribute for lxml.html

Tags:

python

xpath

lxml

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.

like image 675
user3196332 Avatar asked Mar 18 '14 03:03

user3196332


2 Answers

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
like image 156
James Mills Avatar answered Oct 17 '22 15:10

James Mills


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()')
like image 1
Charles Duffy Avatar answered Oct 17 '22 17:10

Charles Duffy