url地址:https://www.sogou.com/ 编写一个简单的爬虫程序,要求用户输入一个搜索关键字,然后将爬取到的搜狗网站上的搜索结果保存在本地文件 “【关键字】.html”中。例如,搜索关键词为“熊猫”,则搜索结果本地保存为“熊猫.html”。
时间: 2024-04-21 22:28:43 浏览: 18
好的,我可以为您编写一个简单的爬虫程序,使用 Python 和 requests、BeautifulSoup 库,实现输入搜索关键字后爬取搜狗搜索结果并保存到本地文件中。以下是代码示例:
```python
import requests
from bs4 import BeautifulSoup
keyword = input("请输入搜索关键字:")
url = "https://www.sogou.com/web"
params = {
"query": keyword
}
response = requests.get(url, params=params)
soup = BeautifulSoup(response.text, "html.parser")
search_result = soup.find_all("div", class_="vrwrap")
filename = f"{keyword}.html"
with open(filename, "w", encoding="utf-8") as f:
f.write(str(search_result))
print(f"搜索结果已保存至 {filename}")
```
以上代码中,我们首先通过 input() 函数获取用户输入的搜索关键字,然后使用 requests 库发送 GET 请求,将搜索关键字作为参数传递给搜狗搜索的 URL,获取搜索结果页面的 HTML 内容。
接着,使用 BeautifulSoup 库解析 HTML 内容,筛选出所有搜索结果的 div 元素,并将其保存到 search_result 变量中。最后,使用 open() 函数创建一个以搜索关键字命名的 HTML 文件,并将搜索结果写入文件中。
完成保存操作后,程序会输出提示信息,告知用户搜索结果已保存至本地文件中。
相关推荐
![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)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)