漂亮的汤过滤函数找不到一个标签页的所有行

2024-10-02 14:21:47 发布

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

我正在尝试使用pythonbeautifulsoup4库解析一个大型html文档。在

页面包含一个非常大的表,其结构如下:

<table summary='foo'>
    <tbody>
        <tr> 
            A bunch of data 
        </tr>
        <tr>
            More data 
        </tr>
        .
        .
        .
        100s of <tr> tags later
    </tbody>
</table>

我有一个函数,用于评估soup.descendants中的给定标记是否是我要查找的类型。这是必要的,因为页面很大(beauthulsoup告诉我文档包含大约4000个标记)。 是这样的:

^{pr2}$

我的问题是,当我迭代soup.descendants时,当我知道<tr>标记继续存在数百行时,函数只为表中的前77行返回{}。在

这是我的函数有问题还是有什么我不明白的关于beauthoulsoup如何生成它的后代集合的?我怀疑这可能是Python或bs4内存问题,但我不知道如何进行故障排除。在


Tags: of函数文档标记datahtmltable页面
1条回答
网友
1楼 · 发布于 2024-10-02 14:21:47

更像是一个有教养的猜测,但我会试试看。在

BeautifulSoup解析HTML的方式很大程度上取决于underlying parser。如果您不specify it explicitlyBeautifulSoup将根据内部排名自动选择一个:

If you don’t specify anything, you’ll get the best HTML parser that’s installed. Beautiful Soup ranks lxml’s parser as being the best, then html5lib’s, then Python’s built-in parser.

在您的情况下,我会尝试切换解析器,看看您会得到什么结果:

soup = BeautifulSoup(data, "lxml")  # needs lxml to be installed
soup = BeautifulSoup(data, "html5lib")  # needs html5lib to be installed
soup = BeautifulSoup(data, "html.parser")  # uses built-in html.parser

相关问题 更多 >