爬取百度热搜
时间: 2025-03-16 22:05:06 浏览: 51
### 如何用Python爬取百度热搜榜
通过 Python 实现爬取百度热搜榜数据的任务可以分为几个部分完成,包括请求网页、解析 HTML 数据以及存储结果到 CSV 文件中。以下是完整的解决方案:
#### 请求网页
为了访问百度热搜页面并获取其内容,通常会使用 `requests` 库发送 HTTP 请求。需要注意的是,在实际操作过程中可能需要设置 User-Agent 来模拟浏览器行为。
```python
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get('https://top.baidu.com/board?tab=realtime', headers=headers)
html_content = response.text
```
此代码片段展示了如何向百度热搜榜单发起 GET 请求,并将返回的内容存入变量 `html_content` 中[^2]。
#### 解析HTML数据
利用 Beautiful Soup 工具包来提取所需的信息。这里假设目标是从实时热榜上抓取排名靠前的关键字及其热度值。
```python
soup = BeautifulSoup(html_content, 'lxml')
hot_search_list = []
for item in soup.select('.category-wrap_iQLoo .c-single-text-ellipsis'):
title = item.text.strip()
hot_value = item.find_next_sibling().text.replace(',', '')
entry = {'title': title, 'value': int(hot_value)}
hot_search_list.append(entry)
print(f'共找到 {len(hot_search_list)} 条记录')
```
上述脚本遍历了所有符合条件的标签节点,分别读取出词条名称与对应的数值字段,最后形成列表形式的结果集。
#### 存储至CSV文件
当收集好全部条目之后,下一步就是把这些信息导出成易于阅读和分享的形式——比如 CSV 表格文档。
```python
import csv
from datetime import datetime
now = datetime.now().strftime('%Y%m%d_%H%M%S')
filename = f'baidu_hotsearch_{now}.csv'
with open(filename, mode='w', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=['title', 'value'])
writer.writeheader()
writer.writerows(hot_search_list)
print(f'{filename} 创建成功!')
```
该段落说明怎样把之前整理出来的资料写进本地磁盘上的新建立档案里去。
---
阅读全文
相关推荐

















