要使用Python爬取包含特定关键词的网页,你可以遵循以下步骤:
导入库
import requests
from bs4 import BeautifulSoup
发送HTTP请求
url = f"https://www.example.com/search?q={keyword}" 将example.com替换为实际网站,keyword替换为要搜索的关键词
response = requests.get(url)
content = response.content
解析HTML内容
soup = BeautifulSoup(content, 'html.parser')
搜索关键词
keywords = soup.find_all(text=keyword) 将keyword替换为要搜索的关键词
提取关键词信息(如果需要):
for keyword in keywords:
parent_tag = keyword.parent 提取相关信息
处理搜索结果(如果需要):
例如,提取所有包含关键词的链接
results = soup.find_all('a', {'class': 'link'}) 根据实际情况修改标签和属性
for result in results:
print(result.get('href')) 打印链接
请根据实际需要修改上述代码中的网址、关键词和搜索逻辑。注意,爬取网站时应遵守网站的`robots.txt`规则,并尊重版权和隐私政策。