首页 > 解决方案 > 使用 Beautiful Soup 解析 XML 的问题

问题描述

当试图用 Beautiful Soup 替换 XML 中的某些元素时,我发现我必须使用它soup.find_all().string.replace_with()来替换所需的元素。但是,我遇到了该soup.find_all()方法仅返回 type 元素的问题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.

如果有人能指出问题所在,我会很高兴。

提前致谢

标签: xmlpython-3.xbeautifulsoup

解决方案


好吧,我不确定您正在寻找什么作为输出,但是您可以通过以下方式替换标签属性:

from bs4 import BeautifulSoup as BS

xml = """
<xml>
    <test tag="0"/>
    <test tag="1"/>
</xml>"""

replace_list = ['0']
replacement = '2'

soup = BS(xml, 'xml')
for elem in soup.find_all("test"):
    if elem['tag'] in replace_list:
        elem['tag'] = replacement
    #print('Element {} has type {}.'.format(elem, elem.name))

xml = str(soup)

print (xml)

输出:

<?xml version="1.0" encoding="utf-8"?>
<xml>
<test tag="2"/>
<test tag="1"/>
</xml>

推荐阅读