【问题标题】:BeautilulSoup Insert a tag and children of this new tag with associated valueBeautilulSoup 插入一个标签和这个新标签的子标签及其关联值
【发布时间】:2021-01-15 21:31:13
【问题描述】:

我需要更新一个 XML 文件。它的结构是

<product sku="xyz">
...
  <custom-attributes>
  <custom-attribute name="attrib1">test</custom-attribute>
...
  </custom-attributes>
</product>

我想添加一条具有多值自定义属性的行,因此所需的结构如下所示:

<custom-attributes>
  <custom-attribute name="attrib1">test</custom-attribute>
  ...
  <custom-attribute name="new1">
    <value>word1</value>
    <value>word2</value>
    ....
  </custom-attribute>
</custom-attributes>

我写了下面的python代码

precision = {"name" : "new1"}

for sku in soup.find_all('product'):
    tagCustoms = sku.find('custom-attributes')
    mynewtag = soup.new_tag('custom-attribute', attrs = precision)
    tagCustoms.append(mynewtag)
    for word in words:   # words is a list
        mynewtag.insert(1,soup.new_tag('value'))

它可以工作......除了我找不到如何定义值标签中的内容......如何在同一个循环中从单词列表中分配每个单词?

我被这个结果卡住了

  <custom-attribute name="new1">
    <value></value>
    <value></value>
    ....
  </custom-attribute>
</custom-attributes>

我试过这段代码

for sku in soup.find_all('product'):
    tagCustoms = sku.find('custom-attributes')
    mynewtag = soup.new_tag('custom-attribute', attrs = precision)
    tagCustoms.append(mynewtag)
    for word in words:   # words is a list
        mynewtag.insert(1,soup.new_tag('value'))
        mynewtag.value.string = word

但它只将列表的第一个单词添加到第一个值标签。

在此先感谢

【问题讨论】:

    标签: python-3.x xml beautifulsoup


    【解决方案1】:

    有几种方法可以解决这个问题,但试试这个,看看它是否有效。

    将您的 for 循环更改为:

    for word in words:   
            ntag = soup.new_tag('value')
            ntag.string = word
            mynewtag.insert(1,ntag)
    

    【讨论】:

    • 好的,我很困惑,以为你“插入”或“附加”有参数来添加这个!谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    相关资源
    最近更新 更多