使用tweepy爬取Twitter导入pandas仅得118行且无法按指定日期范围筛选怎么办
问题根因
- 你当前调用的
api.search属于Twitter免费标准搜索接口,本身权限仅支持抓取最近7天的公开推文,完全不支持检索7天以前的历史内容,你拿到固定118条近期数据是接口的默认返回上限,不是代码逻辑错误。 - 代码中主动注释掉了
until = date_until参数,即使接口有权限查历史内容,当前配置也无法实现截止时间的筛选。 - 原代码存在列名逻辑错配:把情感极性分数的列与分类列名倒置、存在拼写错误(
Nuetral),数据导出后列和内容不对应;且脚本末尾的df.head(1000)无实际输出作用,无法反馈实际抓取的数据量。
修正后可运行代码
import tweepy import pandas as pd from textblob import TextBlob from datetime import datetime # 替换为你自己的API凭证 consumer_key = " " consumer_secret = " " access_token = " " access_token_secret = " " auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) # 开启速率限制自动等待,避免触发接口封禁 api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) # 时间参数格式校验:接口要求时间为UTC时区字符串,格式为YYYY-MM-DD date_since = datetime.strptime("2019-01-01", "%Y-%m-%d").strftime("%Y-%m-%d") date_until = datetime.strptime("2020-01-01", "%Y-%m-%d").strftime("%Y-%m-%d") # 全量历史搜索需对应API权限,免费标准搜索请换回api.search,仅支持近7天内容 tweets = tweepy.Cursor( api.search_all, q="Shopify (canada OR canadian)", since=date_since, until=date_until, tweet_mode="extended", lang="en" # 可通过.items(最大抓取数)设置爬取上限,例如.items(10000)即最多爬取1万条 ).items() user_data = [] for tweet in tweets: # 单次计算情感值,避免重复调用TextBlob拖慢爬取速度 sentiment_score = TextBlob(tweet.full_text).sentiment[0] if sentiment_score > 0: sentiment_class = "Positive" elif sentiment_score < 0: sentiment_class = "Negative" else: sentiment_class = "Neutral" user_data.append([ tweet.created_at, tweet.user.name, tweet.user.location, tweet.full_text, sentiment_score, sentiment_class ]) df = pd.DataFrame( data=user_data, columns=['Created At', "User", 'Location', 'Text', 'Sentiment Score', 'Sentiment Class'] ) # 导出前二次过滤,剔除接口返回的时间范围外的异常数据 df = df[ (df["Created At"] >= pd.to_datetime(date_since, utc=True)) & (df["Created At"] < pd.to_datetime(date_until, utc=True)) ] df.to_excel("output.xlsx", index=False) print(f"共导出 {len(df)} 条符合时间范围的推文")
落地注意事项
- 若需抓取2019-2020这类超出7天范围的历史数据,必须申请对应权限的Twitter API(学术研究版/付费版全量检索接口),才能正常调用代码中的
api.search_all端点;如果仅使用免费标准接口,无论怎么修改代码,都无法获取7天前的历史数据。 - 接口的
until参数为排他边界,即返回的推文只会严格小于该时间点,不会包含当天内容,新增的二次过滤逻辑可避免边界数据混淆。 - 修正后的代码理顺了原有的列名错配问题,导出的表格会严格对应数据类型,不会出现极性分数和分类标签错位的情况。
内容的提问来源于stack exchange,提问作者rabby26
相关产品推荐
相关产品推荐

