首页 > 解决方案 > 精确文本匹配 if 语句 python beautifulsoup

问题描述

我正在尝试使用以下代码查找“精确文本匹配”。该网站是:https ://www.girafferestaurant.co.nz/menu 。当我打印 (soup.find_all(text=True)) 时,我可以取回文本并进行搜索,但我只想匹配或不匹配,具体取决于单词/短语(在本例中为“在 Giraffe 提供”)是否在陈述。

以下是我尝试过的。

text = soup.find_all(text=True)
if 'offering at Giraffe' in text:
     print ("Match")
else: 
     print ("No Match")

另外,我使用了 text = soup.find_all('p') 但文本并不总是在 p 标签中,因为它跨越不同的站点。

标签: pythonbeautifulsoupstring-matching

解决方案


有几种方法可以通过文本搜索BeautifulSoup

  • 搜索功能。使用函数作为text值:

    results = soup.find_all(text=lambda text: text and 'offering at Giraffe' in text)
    
  • 正则表达式。使用正则表达式模式作为text值:

    import re
    
    results = soup.find_all(text=re.compile(r'offering at Giraffe'))
    

推荐阅读