python - BeautifulSoup 找到两个不同的字符串

标签 python beautifulsoup

我目前正在使用 Selenium 和 Beautiful soup 从网站获取所有 HTML 数据。目前,所有数据都存储在 Python 中的变量中。

soup = BeautifulSoup(driver.page_source, 'lxml')

查找两个不同单词出现的最佳方法是什么,要么正好“Open”,要么正好“Closed”,并按照找到的顺序将它们打印到控制台。

我尝试了以下方法:

for node in soup.find_all(text=lambda x: x and "Open" in x):
print(node)

但是我怎样才能让它精确搜索“Closed”

更新了我的代码:

soup = BeautifulSoup(driver.page_source, 'lxml')

status = soup.find('div', attrs={"class":"pagebodydiv"})

with open("status.txt", "w") as file:
    for node in status.find_all(text=lambda t: t in ('Open', 'Closed')):
        file.write(node.encode("utf-8")+"\n")

最佳答案

您可以使用 any() 在这里。

for node in soup.find_all(text=lambda t: t and any(x in t for x in ['Open', 'Closed'])):
    print(node)

这将作为通用解决方案很有用。如果您有更多单词要搜索,只需将它们添加到列表中即可。

如果你想知道什么any()是的,看看 documentation :

any(iterable):

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
<小时/>

编辑:如果您想搜索包含指定单词的句子,请使用上述解决方案。但是,如果您想匹配确切的文本(如编辑的问题中提到的),您可以使用 @Jatimir mentioned in the comments :

for node in soup.find_all(text=lambda t: t in ('Open', 'Closed')):
    print(node)

关于python - BeautifulSoup 找到两个不同的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49779905/

相关文章:

python - 如何将列表值添加到python中的现有字典

Python-Beautiful Soup 不解析整个无序列表

Python:在<br/>之前提取</span>之后的文本

python - 即使通过代理的连接失败,如何重试当前循环

python - BeautifulSoup 实例化超时?

python - 无法使用 post 请求获取某些项目

python - 通过 python 发送时,附件不会显示在 Outlook 中

php - 希望迁移到 Python+Django 的普通 PHP 开发人员 : Directly go with Django or learn the MVC Framework stuff in PHP first?

python - 在 python matplotlib 中绘制公差线

python - 最好的方法是根据元组的第一个元素重新排列元组列表以匹配字符串?