如果 html 页面不包含某个字符串,请使用 BeautifulSoup 检查

EGS*_*EGS 4 python beautifulsoup

我知道可以使用findAll函数在带有 BeautifulSoup 的 html 页面中查找字符串。如果目标是 BeautifulSoup 站点,例如:

page = urllib2.urlopen('https://www.crummy.com/software/BeautifulSoup/bs4/doc/')

soup = BeautifulSoup(page, "html.parser")

print soup.findAll(text="python")
Run Code Online (Sandbox Code Playgroud)

结果将是:

[u'python']
Run Code Online (Sandbox Code Playgroud)

但是我如何检查是否没有发生任何事件?是否可能有一个布尔结果?

t.m*_*dam 5

空列表被评估为False,因此您可以只使用 if 语句,例如:

if soup.findAll(text="python") :  
Run Code Online (Sandbox Code Playgroud)

或者如果你想更明确,你可以使用bool并将其转换为布尔值

bool(soup.findAll(text="python"))  
Run Code Online (Sandbox Code Playgroud)

find_all如果text不包含某些字符串, 您也可以使用 lambda来收集标签

soup.find_all(lambda tag: "python" not in tag.text)  
Run Code Online (Sandbox Code Playgroud)

或者,如果您想检查NavigableStrings 中的所有ssoup是否不包含某个字符串,请使用:

all("python" not in s for s in soup.strings)
Run Code Online (Sandbox Code Playgroud)