简体   繁体   中英

Python lxml, matching attributes

I'm having some troubles wrapping my head around lxml. I have some html I want to parse, and I managed to do it, but it doesn't feel like the best way to do it.

I want to extract the value of the value attribute, but only if the value of name is "myInput"

<input name="myInput" value="This is what i want"/>

I manage to do this, but I feel there is a better solution.

doc = html.fromstring(data)
tr = doc.cssselect("input")

for x in tr:
    if x.get("name") == "myInput":
        print(x.get("value"))

You could do it with an XPath:

import lxml.html as LH

content='<input name="myInput" value="This is what i want"/>'

doc=LH.fromstring(content)
for val in doc.xpath("//input[@name='myInput']/@value"):
    print(val)

yields

This is what i want

The XPath used above has the following meaning:

    //input                    # find all input tags
      [@name='myInput']        # such that the name attribute equals myInput
      /@value                  # return the value of the value attribute           

You could use xpath with lxml, here's the example:

f = StringIO(xmlString)
tree = etree.parse(f)
r = tree.xpath('/input[@name="myInput"]/@value')

See this document: http://lxml.de/xpathxslt.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM