python - 使用 BeautifulSoup 提取 CData

标签 python python-3.x beautifulsoup cdata

我正在尝试使用 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/

相关文章:

python - glsl 解析器使用 pyparsing 给出 AttributeErrors

python - 使用 Scapy 过滤 HTTP 数据包

python-2.7 - 如何在Mac上安装BeautifulSoup4到python3

python - 如何将字符串转换为 float ?

python - 占位符返回 gen_array_ops._placeholder(dtype=dtype, shape=shape, name=name)

html - python 3 : How to web scrape text from div that contains multiple class values

python - 如何用scrapy或者beautiful soup提取特定html标签的内容?

Python:将数组转换为整数

python - 无法使用 docker-compose 安装 Python 包

python - 如何使用 split 函数或 Python 中更通用的方式将带有 xml 标签的字符串转换为字典?