url地址:https://www.sogou.com/ 编写一个简单的爬虫程序,要求用户输入一个搜索关键字,然后将爬取到的搜狗网站上的搜索结果保存在本地文件 “【关键字】.html”中。例如,搜索关键词为“熊猫”,则搜索结果本地保存为“熊猫.html”。
时间: 2024-04-21 19:29:30 浏览: 13
好的,以下是一个简单的Python爬虫程序,可以实现您的需求。需要使用到 requests 和 BeautifulSoup 模块,请确保已经安装这两个模块。
```python
import requests
from bs4 import BeautifulSoup
# 用户输入搜索关键字
keyword = input("请输入搜索关键字:")
# 构建请求头
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
# 发送搜索请求
url = "https://www.sogou.com/web"
params = {
"query": keyword,
"ie": "utf8",
"page": 1
}
response = requests.get(url, headers=headers, params=params)
# 解析搜索结果
soup = BeautifulSoup(response.text, "html.parser")
result = soup.find_all("div", class_="vrwrap")
# 将搜索结果保存到本地文件
filename = "{}.html".format(keyword)
with open(filename, "w", encoding="utf-8") as f:
f.write(str(result))
print("搜索结果已保存到本地文件:{}".format(filename))
```
运行程序后,输入您需要搜索的关键字,程序会自动爬取搜狗搜索结果,并将结果保存到本地文件中。请注意,本示例代码仅供参考,实际应用中需要注意爬虫程序的合法性。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)