find_all 驼峰式标签名称 BeautifulSoup 4
find_all with camelCase tag names with BeautifulSoup 4
我正在尝试使用 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>
查找 camel cased/uppercased 标签名称的正确方法是什么?
对于使用 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
我正在尝试使用 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>
查找 camel cased/uppercased 标签名称的正确方法是什么?
对于使用 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