美丽的汤添加带有属性的标签并保存

Beautiful soup add a tag with attributes and save it

使用 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">

非常感谢

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

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>