首页 > 解决方案 > 如何使用 BeautifulSoup 在 html 页面源代码中搜索特定关键字?

问题描述

我的目标是找出如何在 html 页面源代码中搜索特定关键字并将值返回为 True/False。取决于是否找到了关键字。

我正在寻找的特定关键字是“cdn.secomapp.com”

现在我的代码如下所示:

from urllib import request
from bs4 import BeautifulSoup


url_1 = "https://cheapchicsdesigns.com"
keyword ='cdn.secomapp.com'
page = request.urlopen(url_1)
soup = BeautifulSoup(page)
soup.find_all("head", string=keyword)

但是当我运行它时,它会返回一个空列表:

[]

有人可以帮忙吗?提前致谢

标签: python-3.xurlbeautifulsoupurllib

解决方案


如果您的唯一目的是查看关键字是否存在,那么您不需要构造 BeautifulSoup 对象。

from urllib import request

url_1 = "https://cheapchicsdesigns.com"
keyword ='cdn.secomapp.com'
page = request.urlopen(url_1)

print(keyword in page.read())

但我建议您使用它,requests因为它更容易

import requests

url_1 = "https://cheapchicsdesigns.com"
keyword ='cdn.secomapp.com'

res = requests.get(url_1)

print(keyword in res.text)

推荐阅读