gpt4 book ai didi

python - find_all 带有 BeautifulSoup 4 的 camelCase 标签名称

转载 作者:太空狗 更新时间:2023-10-29 21:46:00 26 4
gpt4 key购买 nike

我正在尝试使用 BeautifulSoup 4.4.0 抓取一个 xml 文件,该文件的标签名称采用驼峰命名法,而 find_all 似乎无法找到它们。示例代码:

from bs4 import BeautifulSoup

xml = """
<hello>
world
</hello>
"""
soup = BeautifulSoup(xml, "lxml")

for x in soup.find_all("hello"):
print x

xml2 = """
<helloWorld>
:-)
</helloWorld>
"""
soup = BeautifulSoup(xml2, "lxml")

for x in soup.find_all("helloWorld"):
print x

我得到的输出是:

$ python soup_test.py
<hello>
world
</hello>

查找驼峰式/大写标签名称的正确方法是什么?

最佳答案

对于使用 BeautifulSoup 的任何区分大小写的解析,您都希望以 "xml" 模式进行解析。默认模式(解析 HTML)不关心大小写,因为 HTML 不关心大小写。在您的情况下,不要使用 "lxml" 模式,而是将其切换为 "xml":

from bs4 import BeautifulSoup

xml2 = """
<helloWorld>
:-)
</helloWorld>
"""
soup = BeautifulSoup(xml2, "xml")

for x in soup.find_all("helloWorld"):
print x

关于python - find_all 带有 BeautifulSoup 4 的 camelCase 标签名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31551158/

26 4 0