首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BeautilulSoup插入带有关联值的新标记的标记和子标记。

BeautilulSoup插入带有关联值的新标记的标记和子标记。
EN

Stack Overflow用户
提问于 2021-01-15 21:31:13
回答 1查看 89关注 0票数 1

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

代码语言:javascript
复制
<product sku="xyz">
...
  <custom-attributes>
  <custom-attribute name="attrib1">test</custom-attribute>
...
  </custom-attributes>
</product>

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

代码语言:javascript
复制
<custom-attributes>
  <custom-attribute name="attrib1">test</custom-attribute>
  ...
  <custom-attribute name="new1">
    <value>word1</value>
    <value>word2</value>
    ....
  </custom-attribute>
</custom-attributes>

我编写了以下python代码

代码语言:javascript
复制
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'))

起作用了..。但我找不到如何在值的标记中定义内容。如何在同一个循环中从单词列表中分配每个单词?

我被这个结果困住了

代码语言:javascript
复制
  <custom-attribute name="new1">
    <value></value>
    <value></value>
    ....
  </custom-attribute>
</custom-attributes>

我试过这段代码

代码语言:javascript
复制
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

但是它只添加列表的第一个单词,第一个值标记。

事先非常感谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-16 01:16:27

有几种方法来处理这个问题,但是尝试一下这个方法,看看它是否有效。

for循环更改为:

代码语言:javascript
复制
for word in words:   
        ntag = soup.new_tag('value')
        ntag.string = word
        mynewtag.insert(1,ntag)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65743801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档