我正在尝试使用 bs4/Python 3 中的 BeautifulSoup 来提取 CData。但是,每当我使用以下内容搜索它时,它都会返回一个空结果。谁能指出我做错了什么?
from bs4 import BeautifulSoup,CData
txt = '''<foobar>We have
<![CDATA[some data here]]>
and more.
</foobar>'''
soup = BeautifulSoup(txt)
for cd in soup.findAll(text=True):
if isinstance(cd, CData):
print('CData contents: %r' % cd)
最佳答案
问题似乎是默认解析器没有正确解析 CDATA。如果您指定了正确的解析器,则会显示 CDATA:
soup = BeautifulSoup(txt,'html.parser')
有关解析器的更多信息,请参阅 the docs
我通过使用 the diagnose function 得到了这个,这the docs推荐:
If you have questions about Beautiful Soup, or run into problems, send mail to the discussion group. If your problem involves parsing an HTML document, be sure to mention what the diagnose() function says about that document.
使用 diagnostic() 函数可为您提供不同解析器如何查看您的 html 的输出,这使您能够为您的用例选择正确的解析器。
关于python - 使用 BeautifulSoup 提取 CData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34639623/