首页 > 解决方案 > BeautifulSoup 字符串搜索

问题描述

我一直在谷歌搜索并查看其他关于在 BeautifulSoup 对象中搜索字符串的问题。

根据我的搜索,以下内容应该检测到字符串 - 但它没有:

strings = soup.find_all(string='Results of Operations and Financial Condition')

但是,以下检测字符串:

tags = soup.find_all('div',{'class':'info'})

for tag in tags:

    if re.search('Results of Operations and Financial Condition',tag.text):

    ''' Do Something'''

为什么一个有效而另一个无效?

标签: pythonbeautifulsoup

解决方案


您可能想使用:

strings = soup.find_all(string=lambda x: 'Results of Operations and Financial Condition' in x)

发生这种情况是因为实现find_all查找您搜索的字符串以完全匹配。我想你可能有一些其他的文字旁边'Results of Operations and Financial Condition'

如果您在此处查看文档,您可以看到您可以为该string参数提供一个函数,并且以下几行似乎是等效的:

soup.find_all(string='Results of Operations and Financial Condition')
soup.find_all(string=lambda x: x == 'Results of Operations and Financial Condition')

推荐阅读