Python 多网站代码搜索:快速高效获取搜索结果
Python 多网站代码搜索:快速高效获取搜索结果
想要同时搜索多个网站的网页内容?本文提供 Python 代码示例,可以帮助你快速高效地实现这一功能。
import requests
from bs4 import BeautifulSoup
# 定义要搜索的关键词和要搜索的网站列表
keyword = 'Python'
websites = ['https://www.google.com', 'https://www.baidu.com', 'https://cn.bing.com']
# 遍历网站列表,搜索关键词并输出结果
for site in websites:
try:
# 发送HTTP请求,获取网页内容
response = requests.get(site, params={'q': keyword})
# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(response.content, 'html.parser')
# 提取搜索结果列表
results = soup.find_all('div', class_='g')
# 输出搜索结果
print('Results from', site)
for result in results:
title = result.find('h3').text
link = result.find('a')['href']
print('-' * 50)
print(title)
print(link)
except:
print('Error occurred while searching', site)
在上面的代码中,我们使用了 requests 模块发送 HTTP 请求,使用 BeautifulSoup 模块解析网页内容,然后提取了搜索结果并输出。你可以通过修改 keyword 和 websites 列表来搜索不同的内容。
使用方法:
- 安装
requests和BeautifulSoup模块:
pip install requests beautifulsoup4
2. 将代码保存为 `search.py` 文件,并运行:
```bash
python search.py
- 你将看到从多个网站搜索到的结果,包括标题和链接。
注意:
- 该代码可能需要根据目标网站的结构进行调整。
- 某些网站可能限制爬虫访问,请遵守网站的使用条款。
总结:
使用 Python 代码可以方便地实现多网站搜索功能,帮助你快速获取相关信息。你还可以根据需要修改代码,添加更多的网站,并进行定制化开发。
原文地址: https://www.cveoy.top/t/topic/mmyi 著作权归作者所有。请勿转载和采集!