Skip to main content
 首页 » 编程设计

python之使用具有奇数 xml 结构的 python 抓取 xml

2025年02月15日8傻小

<attribute> 
  <name>Index</name> 
  <values> 
   <zip> 
     <value>323800</value> 
   </zip> 
   <nation> 
     <value>195300</value> 
   </nation> 
  </values> 
</attribute> 
<attribute> 
 <name>Value_1</name> 
 <values> 
  <nation> 
   <value>193800</value> 
  </nation> 
 </values> 
</attribute> 
<attribute> 
 <name>Value_2</name> 
 <values> 
  <zip> 
   <value>1000</value> 
  </zip> 
  <nation> 
   <value>2000</value> 
  </nation> 
 </values> 
</attribute> 

上面是我正在使用的一个更大的 xml 树的摘录。我想创建一个字典,其中名称标签的文本是键,值是 zip/值。我如何构建代码以仅获取存在 zip 值的属性名称,而忽略没有 zip 值且仅具有国家值的属性名称。

我的代码:

   import urllib2 
   import xml.etree.ElementTree as ET 
   tree = ET.parse(urllib2.urlopen("http://www.sample_xml.com")) 
   # creating list of names 
   names = node.text for node in tree.findall('.//attribute/name')] 
   zip_values = [node.text for node in tree.findall('.//zip/value')] 

从这里我会将两个列表组合成一个字典。但是现在我得到的列表看起来像这样,并且键值不匹配:

   names = ('Index', 'Value_1', 'Value_2') 
   zip_values = ('323800', '1000') 

真正需要的是

   my_dict = ['Index':'323800', 'Value_2':'1000'] 

但是我的代码得到的结果如下。有没有办法解决这个问题?

   my_dict = ['Index':'323800', 'Value_1':'1000', 'Value_2:'Na'] 

请您参考如下方法:

import urllib2 
from lxml import etree 
root = etree.fromstring(urllib2.urlopen("http://www.sample_xml.com").read()) 
# creating list of names 
 
d = {} 
for attribute_node in root.xpath('//attribute[./values/zip/value]'): 
     d[attribute_node.xpath('./name')[0].text] = attribute_node.xpath('./values/zip/value')[0].text 
 
print d # {'Index':'323800', 'Value_2':'1000'}