Python爬虫实现:抓取微博数据
随着互联网的发展,我们现在可以在社交媒体网站上获取大量的信息,包括微博。在本文中,我们将介绍如何使用Python编写一个爬虫程序,来抓取微博数据。这些数据可以用于分析和研究,包括舆论分析、社会热点分析等。
1. 技术准备
在编写爬虫程序之前,我们需要准备一些必要的工具。首先,需要安装Python编程语言和相关的扩展库。这些库包括:requests、beautifulsoup4、pandas、numpy、matplotlib等。这些库可以使用pip命令进行安装。
```
pip install requests
pip install beautifulsoup4
pip install pandas
pip install numpy
pip install matplotlib
```
2. 登录微博
在抓取微博数据之前,我们需要登录微博账号来获取相关的权限。如果你已经有了微博账号,可以直接使用Python来模拟登录微博。我们可以使用requests和beautifulsoup4库来实现这一功能。
```
import requests
from bs4 import BeautifulSoup
url = "https://passport.weibo.cn/signin/login"
session = requests.session()
response = session.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
vk = soup.find('input', attrs={'name': 'vk'})['value']
nonce = soup.find('input', attrs={'name': 'nonce'})['value']
payload = {
'username': 'your_username',
'password': 'your_password',
'savestate': '1',
'r': '',
'ec': '',
'pagerefer': '',
'entry': 'mweibo',
'wentry': '',
'loginfrom': '',
'client_id': '',
'code': '',
'qq': '',
'mainpageflag': '1',
'hff': '',
'hfp': '',
'vt': '',
'auto': '',
'nonce': nonce,
'prelt': '148',
'rsakv': '',
'showpin': '',
'su': '',
'service': '',
'servertime': '',
'url': 'https://m.weibo.cn/',
'sp': '',
'sr': '',
'encoding': 'utf-8',
'pagetype': 'login',
'callback': 'sinaSSOController.doLoginCallback',
'vk': vk,
}
headers = {
'User-Agent': '',
'Referer': 'https://m.weibo.cn/',
}
response = session.post(url, headers=headers, data=payload)
if response.status_code == 200:
print('登录成功')
else:
print('登录失败')
```
在这段代码中,我们首先使用requests库发送GET请求获取登录表单页面。然后使用beautifulsoup4库解析HTML文档,从中获取vl和nonce等参数。最后,我们使用POST请求发送表单数据,来模拟登录微博。
3. 抓取微博数据
在登录微博之后,我们可以使用 requests 库来发送HTTP请求,并使用beautifulsoup4库来解析响应内容。在这里,我们将使用requests.get方法来获取微博数据,并使用beautifulsoup4库来解析响应内容。
```
import json
import time
url = "https://m.weibo.cn/api/container/getIndex?containerid=your_container_id&type=uid&value=your_uid&since_id="
headers = {
'User-Agent': '',
}
results = []
max_id = None
for i in range(0, 100):
print('开始获取第{}页数据'.format(i+1))
time.sleep(1)
response = session.get(url + str(max_id), headers=headers)
data = json.loads(response.text)
if data['ok'] != 1:
print('获取数据失败')
break
cards = data['data']['cards']
for card in cards:
if card['card_type'] == 9:
mblog = card['mblog']
result = {
'id': mblog['id'],
'text': mblog['text'],
'created_at': mblog['created_at'],
'reposts_count': mblog['reposts_count'],
'comments_count': mblog['comments_count'],
'attitudes_count': mblog['attitudes_count'],
}
results.append(result)
max_id = cards[-1]['mblog']['id']
```
在这段代码中,我们使用一个循环来遍历页面,每次获取一页微博数据。我们使用了 time.sleep(1) 来控制访问速度,避免被封禁。我们使用 json.loads 方法将响应内容解析为JSON格式。最后,我们筛选出其中类型为9的微博,提取其中的ID、文本、创建时间、评论数、转发数和点赞数等信息,并保存到一个列表中。
4. 数据处理
在抓取微博数据之后,我们需要将其进行进一步的处理和分析。我们可以使用 pandas 和 numpy 库来进行数据处理和分析。
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(results)
df['created_at'] = pd.to_datetime(df['created_at'])
df['date'] = df['created_at'].apply(lambda x: x.date())
df['hour'] = df['created_at'].apply(lambda x: x.hour)
df['month'] = df['created_at'].apply(lambda x: x.month)
reposts = df['reposts_count'].sum()
comments = df['comments_count'].sum()
attitudes = df['attitudes_count'].sum()
print('转发数:', reposts)
print('评论数:', comments)
print('点赞数:', attitudes)
by_date = df.groupby('date').size().reset_index(name='count')
by_hour = df.groupby('hour').size().reset_index(name='count')
by_month = df.groupby('month').size().reset_index(name='count')
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(12, 4))
ax1.pie([reposts, comments, attitudes], labels=['转发数', '评论数', '点赞数'], autopct='%1.1f%%', startangle=90)
ax1.axis('equal')
ax1.set_title('微博数据统计')
ax2.plot(by_date['date'], by_date['count'])
ax2.set_xlabel('日期')
ax2.set_ylabel('微博数量')
ax2.set_title('按日期统计')
ax3.bar(by_hour['hour'], by_hour['count'])
ax3.set_xlabel('时间')
ax3.set_ylabel('微博数量')
ax3.set_title('按小时统计')
plt.show()
```
在这段代码中,我们使用 pandas.DataFrame 构造函数来创建DataFrame对象,并使用 pd.to_datetime 和 apply 方法来处理时间数据。我们使用 groupby 方法对数据进行分组,并使用 size 方法和 reset_index 方法来统计数据。最后,我们使用 matplotlib.pyplot 库来进行可视化展示。
5. 总结
在本文中,我们介绍了如何使用Python编写一个爬虫程序,来抓取微博数据。我们使用了requests、beautifulsoup4、pandas、numpy和matplotlib等库来完成各种功能。通过本文的介绍,你应该已经掌握了如何使用Python来进行微博数据抓取和分析。