我有一个很长的文件,经常重复使用标签。我需要任意数量的两种标记类型的文本(虽然我不需要来自该类型的每个标记的文本)。
下面是xml文件的一个片段:
<key>category</key>
<string>Utilities</string>
<key>description</key>
<string></string>
<key>developer</key>
<string></string>
<key>display_name</key>
<string>PaperCut Client</string>
<key>icon_hash</key>
<string>0db77f1181a63838123e5b25607be0b9b7e32432d11ec3f370ddde1a7807f3fc</string>
<key>installer_item_hash</key>
<string>ebe1f3093bf20f0c6524e79005b37f932dcfe0166a0d740d985450e7a55f9ca0</string>
<key>installer_item_location</key>
<string>PCClient-13.5.dmg</string>
<key>installer_item_size</key>
<integer>45941</integer>
<key>installer_type</key>
<string>copy_from_dmg</string>
<key>installs</key>我需要提取的是键标签的文本,然后紧跟在它后面的字符串标记:
<key>'identifier'</key>
<string>'desired text'</string>我可以通过以下方式返回所有display_name标记:
soup.findAll('key', string="display_name")但这将返回标记和字符串__name。我只需要“display_name”和下面标签中的文本(字符串标记中的文本,例如:“PaperCut客户”)。我怎样才能做到这一点?
发布于 2016-12-10 04:55:18
xml = '''
<key>category</key>
<string>Utilities</string>
<key>description</key>
<string></string>
<key>developer</key>
<string></string>
<key>display_name</key>
<string>PaperCut Client</string>
<key>icon_hash</key>
<string>0db77f1181a63838123e5b25607be0b9b7e32432d11ec3f370ddde1a7807f3fc</string>
<key>installer_item_hash</key>
<string>ebe1f3093bf20f0c6524e79005b37f932dcfe0166a0d740d985450e7a55f9ca0</string>
<key>installer_item_location</key>
<string>PCClient-13.5.dmg</string>
<key>installer_item_size</key>
<integer>45941</integer>
<key>installer_type</key>
<string>copy_from_dmg</string>
<key>installs</key>'''
soup = BeautifulSoup(xml, 'lxml')
keys = soup.find_all('key', string='display_name')
for key in keys:
string = key.next_sibling.next_sibling
print(key.text)
print(string.text)退出:
display_name
PaperCut Client发布于 2016-12-10 03:43:51
如果key和string总是成对出现并保持相同的顺序(我认为应该是这样,否则整个xml文件最终会陷入混乱),您可以这样做:
for key_tag, string_tag in zip(soup.find_all('key'), soup.find_all('string')):
print key_tag.text, string_tag.texthttps://stackoverflow.com/questions/41071603
复制相似问题