使用Tweepy的since参数提取Covaxin相关推文时遇参数错误
问题原因
你遇到的unexpected parameter :since错误,是因为Tweepy调用的Twitter API v1.1标准搜索接口,不支持把since和until作为独立参数传入。日期过滤规则需要直接写到查询字符串q里,用特定语法实现。另外要注意:标准搜索接口只能检索最近7天的推文,如果要获取2020到2022年的历史数据,得用Premium或Enterprise级别的搜索服务。
解决方案
1. 修正日期过滤(适用于最近7天推文)
把日期条件嵌入q参数,格式是since:YYYY-MM-DD和until:YYYY-MM-DD,不用单独传参数:
修改关键代码行:
date_tweets = tweepy.Cursor(api.search_tweets, q="#Covaxin since:2020-03-31 until:2022-01-09", tweet_mode='extended').items(5)
如果要获取从2020-03-31至今的推文,去掉until部分就行:
date_tweets = tweepy.Cursor(api.search_tweets, q="#Covaxin since:2020-03-31", tweet_mode='extended').items(5)
2. 获取2020-2022年的历史推文
因为标准搜索只能查7天内的数据,要拿更早的历史推文,你需要:
- 升级到Twitter Developer平台的Premium/Enterprise计划
- 用Tweepy调用Premium搜索接口,示例如下(记得替换你的环境名称):
date_tweets = tweepy.Cursor(api.search_full_archive, environment_name="你的Premium环境名", query="#Covaxin since:2020-03-31 until:2022-01-09", tweet_mode='extended').items(5)
完整修正代码(最近7天场景)
import tweepy import pandas as pd # 替换为你的开发者凭证 consumer_key = "wwww" consumer_secret = "xxxx" access_key = "yyyy" access_secret = "zzzz" # 认证流程 auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) # 整合日期条件到查询词中 date_tweets = tweepy.Cursor(api.search_tweets, q="#Covaxin since:2020-03-31", tweet_mode='extended').items(5) tweet_list = [] for tweet in date_tweets: text = tweet._json["full_text"] refined_tweet = { 'text': text, 'favorite_count': tweet.favorite_count, 'retweet_count': tweet.retweet_count, 'created_at': tweet.created_at } tweet_list.append(refined_tweet) df = pd.DataFrame(tweet_list) print(df) df.to_csv('refined_tweets.csv')
注意:别用list当变量名,它是Python内置类型,容易出问题,这里改成了tweet_list。
内容的提问来源于stack exchange,提问作者Palash Purkayastha
相关产品推荐
相关产品推荐

