【问题标题】:Beautiful soup add a tag with attributes and save it美汤加属性标签保存
【发布时间】:2021-04-16 05:13:53
【问题描述】:

使用 InterShop XML 文件,我需要使用 Python 和 BeautifulSoup 在标签内添加以下标签。

我想写这个:

valueNouveau = soup.new_tag('custom-attribute', {"name" : "ImagesWEB"},{"xml:lang" : "fr-FR"})
valueNouveau.string = 'chaine'
tagKeywords.append(valueNouveau)

当我这样做时,使用 msg 写入文件时会失败

unsupported operand type(s) for +: 'dict' and 'str' File
"/Users/cchauvin/Documents/Synonymes/Synoymes_etcetera.py", line 116,
in main f_output.write(str(soup))

当我写这个时,一切都运行顺利,我的文件也写好了

valueNouveau = soup.new_tag('custom-Chauvin') 
valueNouveau.string ='chaine' 
tagKeywords.append(valueNouveau)

怎么了?我需要在现有的xml文件中添加这个标签

 <custom-attribute name="ImagesWEB" dt:dt="string" xml:lang="fr-FR">

在此先感谢

【问题讨论】:

    标签: python-3.x beautifulsoup attributes tags append


    【解决方案1】:

    您不需要在唯一字典中传递标签的每个属性,只需创建一个字典并将所需的所有属性放入其中并将其传递给方法。像这样:

    dict_attributes = {"name" : "ImagesWEB",
                "xml:lang" : "fr-FR"}
    valueNouveau = soup.new_tag('custom-attribute',attrs=dict_attributes)
    valueNouveau.string = 'chaine'
    tagKeywords.append(valueNouveau)
    

    输出:

    <custom-attribute name="ImagesWEB" xml:lang="fr-FR">chaine</custom-attribute>
    

    【讨论】:

      猜你喜欢
      • 2018-07-06
      • 2014-06-30
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 2021-09-18
      相关资源
      最近更新 更多