0
我想從多個結構相似的XML標籤中提取信息。我循環每個孩子將其附加到字典。有沒有辦法避免每個標籤的for循環(如我的MWE中的sn和count)。有效的方式來循環標籤與美麗的湯
from bs4 import BeautifulSoup as bs
import pandas as pd
xml = """
<info>
<tag>
<sn>9-542</sn>
<count>14</count>
</tag>
<tag>
<sn>3-425</sn>
<count>16</count>
</tag>
</info>
"""
bs_obj = bs(xml, "lxml")
info = bs_obj.find_all('tag')
d = {}
# I want to avoid these multiple for-loops
d['sn'] = [i.sn.text for i in info]
d['count'] = [i.count.text for i in info]
pd.DataFrame(d)
是否需要xml BeautifulSoup?您正在使用xml。你可以使用xpath和xml。 BeautifulSoup本身不支持XPath表達式。 lxml有一個BeautifulSoup兼容模式,它會嘗試解析破碎的HTML。你爲什麼使用BeautifulSoup?它將會像tree.xpath(「/ tag/sn」)一樣 - 找到標籤「tag」的所有子標籤,標籤的名稱是「sn」 – user565447