使用 BeautifulSoup 遍历列表并创建 XML 标签

Using BeautifulSoup to loop through a list and create XML tags

我有一个年份列表,如下:

year = ['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013']

我正在尝试创建一系列包含在另一个预先存在的标签中的 XML 标签,如下所示:

<intro>
    <exposures>
      <exposure year = "2005"></exposure>
      <exposure year = "2006"></exposure>
      <exposure year = "2007"></exposure>
      <exposure year = "2008"></exposure>
      etc.
    <exposures> 
</intro>

稍后我将在标签中填充内容。现在我正在尝试遍历 year 并将它们添加到标签中,然后将其包含在标签中。

我一直在尝试遍历 'year' 列表并将每个值作为属性附加到标签:

testsoup = BeautifulSoup(testxml, 'xml')
intro_tag = testsoup.intro('intro')
exp_tag = testsoup.exposures('exposures')
year = ['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013']
exposure_tag = testsoup.new_tag('exposure', year = '')
for x in year:    
    exposure_tag['year'] = x
    exp_tag.append(exposure_tag)
    intro_tag.append(exp_tag)

不幸的是,这似乎只附加了列表中的最后一个值:

<intro><exposures><exposure year="2013"/></exposures></intro>

这只是 BeautifulSoup 的一个功能吗?能不能只加一个标签不加多个?我正在使用 BeautifulSoup 4.4.0.

顺便说一句,BeautifulSoup 是最好的方法吗?我看到很多帖子称赞 BS4 和 lxml 的网络抓取能力,但它们似乎都不能用于生成 XML(这不是一件坏事,只是我注意到的)。是否有更好的自动化 XML 生成包?

我怀疑问题出在这一行:exposure_tag = testsoup.new_tag('exposure', year = '')。你有一个标签,你试图多次将它附加到同一个父标签。试试这个。

for x in year:    
    exposure_tag = testsoup.new_tag('exposure', year = x)
    exp_tag.append(exposure_tag)
    intro_tag.append(exp_tag)

我没有查看 BS 源代码,但认为行为是这样的:当您调用 exp_tag.append(smth) 时,您实际上添加了指向 smth 对象的指针。因此,当您仅实例化 exposure_tag 一次时,您会得到一堆指向同一对象的指针。当你在 exposure_tag['year'] = x 中修改那个对象时,它会影响 BS 内部列表结构的所有元素。

因此,解决方案是在每一步中创建新的对象实例:

testsoup = BeautifulSoup(testxml, 'xml')
intro_tag = testsoup.intro('intro')
exp_tag = testsoup.exposures('exposures')
year = ['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013']
for x in year:    
    exposure_tag = testsoup.new_tag('exposure', year = x)
    exp_tag.append(exposure_tag)
    intro_tag.append(exp_tag)  # BTW: Are you sure you need this here?