首页 > 解决方案 > Python BeautifulSoup - find_all 捕获由空格和新行包围的字符串

问题描述

我有以下 HTML 片段,它们是更大的 HTML 页面的一部分:

<tr >
    <th class="left">
        <span tooltip haspopup="true" class="tip" title="A type of fruit">Oranges</span>:
    </th>
    <td class="reduce">
        Seven
    </td>
</tr>

<tr >
    <th class="left">
        Apples
    </th>
    <td>
        Three
    </td>
</tr>

当我执行代码时:

soup.find_all(string='Oranges')

我得到:

['Oranges']

这是完美的。

但是,当我执行代码时:

soup.find_all(string='Apples')

我得到:

[]

为什么这不起作用?我感觉这与 HTML 代码的“Apples”位周围的空格和换行符等有关,但是我无法抓住它。我已经尝试了以下没有结果的方法。

soup.find_all(string='\n        Apples\n    ')

soup.find_all(string='        Apples    ')

soup.find_all(string='         Apples     ')

感谢您的帮助!谢谢。

Ps 我不认为这很重要,但最终我使用“findParent().fetchNextSiblings()[0].text.strip()”或类似的方法来获得“七”和“三” - 它适用于前一种情况,但不是后一种情况。

标签: pythonbeautifulsoup

解决方案


尝试:

import re
...

soup.find_all(text = re.compile(r"Apples", re.IGNORECASE))

推荐阅读