xml - 使用 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.
如果有人能指出问题所在,我会很高兴。
提前致谢
解决方案
好吧,我不确定您正在寻找什么作为输出,但是您可以通过以下方式替换标签属性:
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>
推荐阅读
- javascript - 如何将数组转换为对象?
- amazon-web-services - Routing or redirecting partial path in API gateway proxy to Lambda
- java - 导航视图项目在按下时不会响应
- javascript - Tooltip text not showing after replace()
- regex - 正则表达式帮助。捕获以“score”开头并以数字结尾的字符串
- c++ - C++ Operator overloading, returns, types and robots
- ios - Apply Beveled Radial Gradient to UIView
- ios - 用 PDFKit 实现 PencilKit
- java - 如何删除默认的搜索栏笔划?
- c++ - C++20:非类型模板参数中的非捕获 lambda