【发布时间】:2019-02-28 14:10:14
【问题描述】:
当尝试用 Beautiful Soup 替换 XML 中的某些元素时,我发现我必须使用 soup.find_all().string.replace_with() 来替换所需的元素。但是,我遇到了soup.find_all() 方法只返回None 类型的元素的问题。
所以我试图将我的问题分解为尽可能基本的 XML:
from bs4 import BeautifulSoup as BS
xml = """
<xml>
<test tag="0"/>
<test tag="1"/>
</xml>"""
soup = BS(xml, 'xml')
for elem in soup.find_all("test"):
print('Element {} has type {}.'.format(elem, elem.type))
这给出了完全相同的东西:
Element <test tag="0"/> has type None.
Element <test tag="1"/> has type None.
如果有人能指出问题所在,我会很高兴。
提前致谢
【问题讨论】:
-
你想在这里替换什么?
-
您还想使用
.name代替吗?print('Element {} has type {}.'.format(elem, elem.name)) -
对不起,应该说得更清楚。我想要做的是替换,例如,
tag="0"withtag="2"。在这个例子中,我将通过在 for 循环中使用elem.string.replace_with('test tag="2"')来做到这一点。然而,这只是给AttributeError: 'NoneType' object has no attribute 'replace_with'。 -
好的,我在底部放了一个解决方案。这应该可以让您继续前进,但我会对其进行调整以反映您提供的示例输出
-
问题是,
"test tag="2"不是该标签/元素中的字符串/文本。这是一个属性。所以你真正想要替换的不是字符串/文本,而是属性值
标签: xml python-3.x beautifulsoup