我目前正在使用 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):
block 引用> <小时/>Return
True
if any element of the iterable is true. If the iterable is empty, returnFalse
. 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/