Python爬取微博数据实战教程(附完整代码)
包含编程籽料、学习路线图、爬虫代码、安装包等!【点击领取】
一、前言
微博作为中国最大的社交媒体平台之一,蕴含着丰富的公开数据。本文将详细介绍如何使用Python爬取微博数据,包括用户信息、微博内容、评论等,并提供完整的代码实现。
二、准备工作
- 需要安装的库
pip install requests beautifulsoup4 selenium pandas - 其他准备
注册微博开发者账号(可选)
安装Chrome浏览器和对应版本的ChromeDriver
三、微博爬取的3种方法
方法1:通过移动端API爬取(推荐)
import requests import json defget_weibo_content(user_id, max_page=5): headers ={'User-Agent':'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'}for page inrange(1, max_page+1): url =f'https://m.weibo.cn/api/container/getIndex?uid={user_id}&type=uid&page={page}' response = requests.get(url, headers=headers)if response.status_code ==200: data = json.loads(response.text) weibos = data['data']['cards']for weibo in weibos:if'mblog'in weibo: content = weibo['mblog']['text']print(content)else:print(f"请求失败,状态码:{response.status_code}")# 使用示例(替换为真实用户ID) get_weibo_content('1234567890')方法2:使用Selenium模拟浏览器
from selenium import webdriver from selenium.webdriver.common.by import By import time defselenium_weibo_spider(keyword): driver = webdriver.Chrome() url =f'https://s.weibo.com/weibo?q={keyword}' driver.get(url)# 等待页面加载 time.sleep(5)# 获取微博内容 weibos = driver.find_elements(By.XPATH,'//div[@class="card-wrap"]')for weibo in weibos[:10]:# 只取前10条try: content = weibo.find_element(By.XPATH,'.//p[@class="txt"]').text print(content.strip())except:continue driver.quit()# 使用示例 selenium_weibo_spider('Python')方法3:使用官方API(需要开发者权限)
import requests defofficial_api_spider(access_token): url ='https://api.weibo.com/2/statuses/public_timeline.json' params ={'access_token': access_token,'count':100} response = requests.get(url, params=params)if response.status_code ==200: data = response.json()for status in data['statuses']:print(f"用户:{status['user']['screen_name']}")print(f"内容:{status['text']}")print("---")else:print(f"请求失败:{response.status_code}")# 使用示例(需要替换为真实access_token)# official_api_spider('your_access_token')四、数据解析与清洗
- 处理HTML标签
from bs4 import BeautifulSoup defclean_html(content): soup = BeautifulSoup(content,'html.parser')# 移除所有HTML标签 text = soup.get_text()# 替换多余空白 text =' '.join(text.split())return text - 处理表情符号
import re defremove_emoji(text): emoji_pattern = re.compile("["u"\U0001F600-\U0001F64F"# emoticonsu"\U0001F300-\U0001F5FF"# symbols & pictographsu"\U0001F680-\U0001F6FF"# transport & map symbolsu"\U0001F1E0-\U0001F1FF"# flags (iOS)"]+", flags=re.UNICODE)return emoji_pattern.sub(r'', text)五、数据存储
- 存储到CSV文件
import pandas as pd defsave_to_csv(data, filename='weibo_data.csv'): df = pd.DataFrame(data) df.to_csv(filename, index=False, encoding='utf_8_sig')print(f"数据已保存到{filename}")- 存储到MySQL数据库
import pymysql defsave_to_mysql(data): connection = pymysql.connect( host='localhost', user='root', password='password', database='weibo_data')try:with connection.cursor()as cursor: sql ="INSERT INTO weibo (content, user, time) VALUES (%s, %s, %s)" cursor.executemany(sql, data) connection.commit()finally: connection.close()六、反爬虫策略应对
- 请求头设置
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','Referer':'https://weibo.com/','Cookie':'你的Cookie'}- 使用代理IP
proxies ={'http':'http://127.0.0.1:1080','https':'http://127.0.0.1:1080'} response = requests.get(url, headers=headers, proxies=proxies)- 设置请求间隔
import random import time defrandom_delay(): time.sleep(random.uniform(1,3))七、完整案例:爬取某话题下的微博
import requests import pandas as pd from bs4 import BeautifulSoup import time import random defget_weibo_topic(topic, pages=5): base_url ='https://s.weibo.com/weibo' 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'} all_data =[]for page inrange(1, pages+1): params ={'q': topic,'page': page } response = requests.get(base_url, params=params, headers=headers)if response.status_code !=200:print(f"第{page}页请求失败")continue soup = BeautifulSoup(response.text,'html.parser') cards = soup.find_all('div', class_='card-wrap')for card in cards:try: content = card.find('p', class_='txt').get_text(strip=True) user = card.find('a', class_='name').get_text(strip=True) time_text = card.find('p', class_='from').get_text(strip=True) all_data.append({'用户': user,'内容': content,'时间': time_text })except Exception as e:print(f"解析出错: {e}")continueprint(f"第{page}页完成") time.sleep(random.uniform(2,5)) df = pd.DataFrame(all_data) df.to_excel(f'{topic}_微博数据.xlsx', index=False)print(f"数据已保存到{topic}_微博数据.xlsx")# 使用示例 get_weibo_topic('Python编程', pages=3)八、总结
本文介绍了三种爬取微博数据的方法:
通过移动端API(最简单高效)
使用Selenium模拟浏览器(适合动态加载内容)
官方API(最稳定但需要申请权限)
建议初学者从移动端API开始尝试,遇到问题时可以结合Selenium解决。完整代码已提供,可以直接运行测试。
最后:
希望你编程学习上不急不躁,按照计划有条不紊推进,把任何一件事做到极致,都是不容易的,加油,努力!相信自己!
文末福利
最后这里免费分享给大家一份Python全套学习资料,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
包含编程资料、学习路线图、源代码、软件安装包等!【点击这里】领取!
① Python所有方向的学习路线图,清楚各个方向要学什么东西
② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析
③ 100多个Python实战案例,学习不再是只会理论
④ 华为出品独家Python漫画教程,手机也能学习