用beauthulsoup提取CD

2024-04-25 22:01:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用bs4/python3中的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)

Tags: 方法fromimporttxthavecdsomepython3
1条回答
网友
1楼 · 发布于 2024-04-25 22:01:56

问题似乎是默认解析器无法正确解析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.

使用diagnose()函数可以输出不同解析器如何查看html,这使您能够为您的用例选择正确的解析器。在

相关问题 更多 >