使用 Python 爬虫抓取微博数据的详细步骤(2025最新版)
本文介绍了两种Python抓取微博数据的方法:1)通过分析XHR接口使用Requests获取JSON数据,需处理Cookie和反爬;2)使用Selenium模拟浏览器操作抓取页面内容。文章对比了三种抓取方式的优缺点,推荐API接口或Selenium方案,并详细说明了环境准备、Cookie获取、代码实现步骤及注意事项。数据目标包括微博内容、用户、发布时间和链接,最终可导出为CSV文件。两种方法各具特
📌 前言
微博作为中国最活跃的社交平台之一,拥有丰富的实时热点、用户动态和评论信息。但由于其强大的反爬策略,抓取微博数据并不像抓取一般静态页面那么容易。本文将手把手教你如何使用 Python 抓取微博数据,包括使用 API 接口、处理 Cookie 和模拟登录等。
✅ 抓取微博数据的三种常见方式
| 抓取方式 | 是否推荐 | 说明 |
|---|---|---|
| 使用微博开放API | ✅ 推荐 | 需注册开发者账号,接口稳定,适合合规抓取 |
| 分析网页接口(XHR) | ⚠️ 可用 | 需要处理 Cookie 和签名,有一定难度 |
| 使用 Selenium 模拟浏览器 | ✅ 稳定 | 对抗 JS 渲染和反爬,适合评论、滚动数据 |
本文主要介绍第 2 和 3 种方法,更灵活、可控性强。
🧰 环境准备
pip install requests
pip install beautifulsoup4
pip install selenium
pip install pandas
pip install fake-useragent
浏览器驱动推荐使用 ChromeDriver,对应你的 Chrome 版本,下载地址:
👉 https://chromedriver.chromium.org/downloads
📍 实战目标
抓取指定关键词(如“高考”)的微博搜索结果,包括:
- 微博内容
- 发布时间
- 用户昵称
- 微博链接
🚀 实战一:使用 Requests + 浏览器抓包 获取接口数据
第一步:打开微博搜索页面
前往:
https://s.weibo.com/weibo?q=高考
F12 打开开发者工具 → Network → XHR,查看接口,如:
https://s.weibo.com/ajax/...
这些接口返回 JSON 数据,但需要携带 Cookie 和 User-Agent,否则返回为空或提示“请登录”。
第二步:抓取数据代码示例
import requests
import pandas as pd
from fake_useragent import UserAgent
# 浏览器登录后手动复制 Cookie
cookies = {
"SUB": "你的SUB值",
# 可添加其他关键 cookie
}
headers = {
"User-Agent": UserAgent().random,
"Referer": "https://s.weibo.com",
}
query = "高考"
url = f"https://s.weibo.com/ajax/statuses/search?keyword={query}&page=1"
res = requests.get(url, headers=headers, cookies=cookies)
data = res.json()
results = []
for card in data["data"]["list"]:
text = card.get("text_raw", "")
user = card["user"]["screen_name"]
created_at = card["created_at"]
mid = card["mid"]
link = f"https://weibo.com/{card['user']['id']}/{mid}"
results.append([user, created_at, text, link])
df = pd.DataFrame(results, columns=["用户", "发布时间", "内容", "链接"])
df.to_csv("微博搜索_高考.csv", index=False, encoding="utf-8-sig")
⚠️ 注意事项:
- 必须登录微博后复制 Cookie,否则接口返回空列表。
- 每次请求不可过快,建议加上
time.sleep()。 text_raw是去除 HTML 标签的原文。
🖥️ 实战二:使用 Selenium 模拟搜索抓取微博内容(适合不分析接口)
步骤:
- 使用 Selenium 打开微博搜索页面
- 模拟滚动加载微博
- 使用 BeautifulSoup 或 XPath 抓取内容
示例代码:
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import pandas as pd
options = webdriver.ChromeOptions()
options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(options=options)
keyword = "高考"
driver.get(f"https://s.weibo.com/weibo?q={keyword}")
# 等待加载
time.sleep(3)
# 模拟下拉滚动多次
for i in range(5):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2)
posts = driver.find_elements(By.CSS_SELECTOR, "div.card-wrap")
data = []
for post in posts:
try:
text = post.find_element(By.CSS_SELECTOR, ".content").text
user = post.find_element(By.CSS_SELECTOR, ".name").text
timeinfo = post.find_element(By.CSS_SELECTOR, ".from").text
data.append([user, timeinfo, text])
except:
continue
driver.quit()
df = pd.DataFrame(data, columns=["用户", "时间", "内容"])
df.to_csv("selenium_微博数据.csv", index=False, encoding="utf-8-sig")
🔒 关于 Cookie 获取方式
你可以通过如下方法获取登录后的 Cookie:
- 登录微博 → 按 F12 → Application → Cookies
- 找到名为
SUB的 Cookie - 复制其值,填入代码中的 cookies 字典
也可以使用 Selenium 登录后用 driver.get_cookies() 获取完整 Cookie。
🧠 总结
| 工具 | 适合场景 | 难度 | 稳定性 |
|---|---|---|---|
| Requests + 接口 | 抓取热搜/搜索结果 | ⭐⭐⭐⭐ | ⭐⭐⭐ |
| Selenium | 抓取评论、动态加载页面 | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| 官方 API | 合规授权使用 | ⭐⭐ | ⭐⭐⭐⭐⭐ |
📚 延伸学习推荐
- 微博反爬机制详解与应对策略
- 构建实时微博爬虫+情感分析系统
- Python + MongoDB 存储海量社交数据
- 微博话题热度趋势图可视化(pyecharts)
💬 最后
抓取微博的数据并不简单,需要你具备 HTML 分析能力、JS 抓包技巧以及对反爬的理解。建议从搜索页的静态数据入手,再逐步挑战评论、私信、用户关系等复杂数据。
更多推荐
所有评论(0)