我的代码出现了一件奇怪的事情:
import lxml.html
myxml='''
<cooperate>
<job DecreaseHour="1" table="tpa_radio_sum">
</job>
<job DecreaseHour="2" table="tpa_radio_sum">
</job>
<job DecreaseHour="3" table="tpa_radio_sum">
</job>
</cooperate>
'''
root=lxml.html.fromstring(myxml)
nodes1=root.xpath('//job[@DecreaseHour="1"]')
nodes2=root.xpath('//job[@table="tpa_radio_sum"]')
print "nodes1=",nodes1
print "nodes2=",nodes2
我得到的是:
nodes1=[]
和
nodes2=[ Element job at 0x1241240,
Element job at 0x1362690,
Element job at 0x13626c0]
为什么nodes1
是[]
?这是一件很奇怪的事情。为什么?
答案 0 :(得分:5)
由于您使用的是html解析器,因此所有属性都会变为小写:
>>> root.xpath("//job")[0].attrib
{'table': 'tpa_radio_sum', 'decreasehour': '1'}
您可以使用真正的xml-parser:
>>> import lxml.etree
>>> root = lxml.etree.fromstring(myxml)
>>> root.xpath('job[@DecreaseHour="1"]')
[<Element job at 0x293daa8>]