您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python如何爬取微博热搜并实现数据可视化
## 目录
1. [项目背景与目标](#项目背景与目标)
2. [技术栈与工具准备](#技术栈与工具准备)
3. [微博热搜数据爬取实战](#微博热搜数据爬取实战)
- [3.1 分析微博网页结构](#31-分析微博网页结构)
- [3.2 使用Requests获取数据](#32-使用requests获取数据)
- [3.3 数据解析与清洗](#33-数据解析与清洗)
4. [数据存储方案](#数据存储方案)
- [4.1 CSV文件存储](#41-csv文件存储)
- [4.2 MySQL数据库存储](#42-mysql数据库存储)
5. [数据可视化实现](#数据可视化实现)
- [5.1 Matplotlib基础图表](#51-matplotlib基础图表)
- [5.2 Pyecharts交互式可视化](#52-pyecharts交互式可视化)
- [5.3 词云图生成](#53-词云图生成)
6. [完整代码示例](#完整代码示例)
7. [项目扩展方向](#项目扩展方向)
8. [常见问题与解决方案](#常见问题与解决方案)
---
## 项目背景与目标
微博热搜作为中文互联网最活跃的舆情风向标,每日吸引超过3亿用户关注。本项目将通过Python技术栈实现:
- 实时爬取微博热搜榜单数据
- 建立结构化存储系统
- 生成多维度的数据可视化图表
- 构建舆情分析基础框架
---
## 技术栈与工具准备
| 工具/库 | 用途 | 版本要求 |
|----------------|-----------------------|----------|
| Python | 主开发语言 | 3.7+ |
| Requests | HTTP请求库 | 2.26+ |
| BeautifulSoup | HTML解析 | 4.10+ |
| PyMySQL | MySQL数据库交互 | 1.0+ |
| Pandas | 数据处理 | 1.3+ |
| Matplotlib | 静态可视化 | 3.5+ |
| Pyecharts | 交互式可视化 | 1.9+ |
| WordCloud | 词云生成 | 1.8+ |
| Jieba | 中文分词 | 0.42+ |
安装命令:
```bash
pip install requests beautifulsoup4 pymysql pandas matplotlib pyecharts wordcloud jieba
<tbody id="pl_top_realtimehot">
<td class="td-01">
<a href="/weibo?q=...">
<span>
import requests
from bs4 import BeautifulSoup
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Cookie': '您的微博Cookie' # 需登录获取
}
def fetch_weibo_hot():
url = 'https://s.weibo.com/top/summary'
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
return response.text
except Exception as e:
print(f"请求失败: {e}")
return None
def parse_hot_data(html):
soup = BeautifulSoup(html, 'html.parser')
tbody = soup.find('tbody', {'id': 'pl_top_realtimehot'})
hot_items = []
for tr in tbody.find_all('tr')[1:]: # 跳过表头
rank = tr.find('td', class_='td-01').get_text(strip=True)
keyword = tr.find('a').get_text(strip=True)
try:
hot_score = tr.find('span').get_text(strip=True)
except AttributeError:
hot_score = '0'
hot_items.append({
'rank': int(rank),
'keyword': keyword,
'hot_score': int(hot_score) if hot_score.isdigit() else 0
})
return hot_items
import pandas as pd
def save_to_csv(data, filename='weibo_hot.csv'):
df = pd.DataFrame(data)
df.to_csv(filename, index=False, encoding='utf_8_sig')
import pymysql
def save_to_mysql(data):
conn = pymysql.connect(
host='localhost',
user='root',
password='123456',
database='weibo_data'
)
with conn.cursor() as cursor:
sql = """CREATE TABLE IF NOT EXISTS hot_search (
id INT AUTO_INCREMENT PRIMARY KEY,
rank INT,
keyword VARCHAR(100),
hot_score INT,
create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)"""
cursor.execute(sql)
for item in data:
insert_sql = "INSERT INTO hot_search (rank, keyword, hot_score) VALUES (%s, %s, %s)"
cursor.execute(insert_sql, (item['rank'], item['keyword'], item['hot_score']))
conn.commit()
conn.close()
import matplotlib.pyplot as plt
def plot_top10(data):
top10 = sorted(data, key=lambda x: x['hot_score'], reverse=True)[:10]
keywords = [x['keyword'] for x in top10]
scores = [x['hot_score'] for x in top10]
plt.figure(figsize=(12, 6))
bars = plt.barh(keywords, scores, color='#FF6B81')
plt.xlabel('热度值')
plt.title('微博热搜TOP10')
# 添加数据标签
for bar in bars:
width = bar.get_width()
plt.text(width, bar.get_y() + bar.get_height()/2, f'{width:,}')
plt.tight_layout()
plt.savefig('top10.png', dpi=300)
from pyecharts.charts import Bar
from pyecharts import options as opts
def create_interactive_chart(data):
top20 = sorted(data, key=lambda x: x['hot_score'], reverse=True)[:20]
bar = (
Bar()
.add_xaxis([x['keyword'] for x in top20])
.add_yaxis("热度值", [x['hot_score'] for x in top20])
.reversal_axis()
.set_global_opts(
title_opts=opts.TitleOpts(title="微博热搜TOP20"),
xaxis_opts=opts.AxisOpts(name="热度"),
yaxis_opts=opts.AxisOpts(
name="关键词",
axislabel_opts=opts.LabelOpts(font_size=8)
)
)
)
return bar.render("hot_search.html")
from wordcloud import WordCloud
import jieba
def generate_wordcloud(data):
text = ' '.join([x['keyword'] for x in data])
word_list = jieba.cut(text)
word_str = ' '.join(word_list)
wc = WordCloud(
font_path='msyh.ttc',
background_color='white',
width=800,
height=600
).generate(word_str)
plt.imshow(wc)
plt.axis('off')
plt.savefig('wordcloud.png', dpi=300)
(此处因篇幅限制展示核心代码,完整代码需包含异常处理、日志记录等)
# weibo_hot_crawler.py
import logging
from datetime import datetime
def main():
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s: %(message)s'
)
try:
html = fetch_weibo_hot()
if html:
data = parse_hot_data(html)
# 数据存储
save_to_csv(data)
save_to_mysql(data)
# 可视化
plot_top10(data)
create_interactive_chart(data)
generate_wordcloud(data)
logging.info(f"成功处理{len(data)}条热搜数据")
except Exception as e:
logging.error(f"程序异常: {e}")
if __name__ == '__main__':
main()
反爬机制:
数据缺失:
编码问题:
可视化渲染:
数据库连接:
通过本项目的实践,读者不仅可以掌握Python爬虫与可视化的核心技能,更能构建一套完整的舆情监测系统原型。建议在合法合规的前提下进行数据采集,注意遵守微博平台的相关使用协议。 “`
注:实际执行时需要注意: 1. 微博需要登录才能获取完整数据,需替换真实的Cookie 2. MySQL连接参数需要根据实际环境配置 3. 字体文件路径需替换为系统存在的字体 4. 建议添加适当的延时避免请求过于频繁
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。