You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用snscraper调用Twitter接口时遭遇403错误的原因排查

问题:snscrape抓取Twitter话题推文时持续返回403错误

我运行以下代码尝试抓取带#python话题的Twitter推文:

import time
import pandas as pd

# pip install snscrape
!pip install snscrape

# Pull Twitter data using SNScrape
import snscrape.modules.twitter as sntwitter

scraper = sntwitter.TwitterSearchScraper("#python")

for tweet in scraper.get_items():
  break

tweet

但持续抛出如下错误:

ERROR:snscrape.base:Error retrieving [Twitter API endpoint]: blocked (403)
CRITICAL:snscrape.base:4 requests to [Twitter API endpoint] failed, giving up.
CRITICAL:snscrape.base:Errors: blocked (403), blocked (403), blocked (403), blocked (403)

ScraperException Traceback (most recent call last)
in <cell line: 12>()
10 scraper = sntwitter.TwitterSearchScraper("#python")
11
---> 12 for tweet in scraper.get_items():
13 break
14
4 frames /usr/local/lib/python3.9/dist-packages/snscrape/base.py in _request(self, method, url, params, data, headers, timeout, responseOkCallback, allowRedirects, proxies)
245 _logger.fatal(msg)
246 _logger.fatal(f'Errors: {", ".join(errors)}')
---> 247 raise ScraperException(msg)
248 raise RuntimeError('Reached unreachable code')
249
ScraperException: 4 requests to [Twitter API endpoint] failed, giving up.

起初我以为是触发速率限制导致IP被封禁,但更换不同网络、设备及账号后错误依旧,请问是否可能是Python或snscraper版本问题导致?


解决方案与分析
  • 版本问题确实可能是核心诱因:

    • 旧版snscraper未适配Twitter API的最新反爬规则或接口变更,建议卸载当前版本后安装最新开发版:
      pip uninstall -y snscrape
      pip install git+https://github.com/JustAnotherArchivist/snscrape.git
      
    • Python版本兼容性:确保使用Python 3.8及以上版本,3.7及以下旧版本可能存在依赖包兼容问题,导致请求头构造不规范触发403拦截。
  • 其他关键排查点:

    • Twitter反爬机制已强化,匿名无登录态的请求会被直接拦截,需在snscrape中配置登录凭据:
      scraper = sntwitter.TwitterSearchScraper("#python", credentials=("你的用户名", "你的密码"))
      
    • 部分环境(如Colab)的默认请求头会被识别为爬虫,可手动添加标准浏览器标识:
      from snscrape.base import Scraper
      Scraper.DEFAULT_HEADERS['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
      

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 20:34:56