value attribute for lxml.html

二次信任 提交于 2020-01-14 13:26:31

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/22469785/value-attribute-for-lxml-html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!