赞
踩
当时使用免费推特api报错:
{‘errors’: [{‘message’: ‘You currently have access to a subset of Twitter API v2 endpoints and limited v1.1 endpoints (e.g. media post, oauth) only. If you need access to this endpoint, you may need a different access level. You can learn more here: https://developer.twitter.com/en/portal/product’, ‘code’: 453}]}
我傻傻的以为,需要购买基本版推特api,才能够访问,购买了基础版api后,结果新的api访问依然出错,还是无权限访问,显示1.1limited
但是仔细看了开发者面板的描述之后,觉得应该没错,能够访问这些结点,只是方式错了
import tweepy # 替换为你自己的API密钥和令牌 consumer_key = 'xxxx' consumer_secret = 'xxxx' access_token = 'xxxx' access_token_secret = 'xxxx' # 使用API密钥和令牌进行身份验证 auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) # 创建API对象 api = tweepy.API(auth) username = 'target_username' # 获取用户对象 user = api.get_user(screen_name=username) # 打印用户信息 print("User ID:", user.id) print("Screen Name:", user.screen_name) print("Name:", user.name) # 获取用户的最新推文 tweets = api.user_timeline(screen_name=username, count=10) print("\nRecent Tweets:") for tweet in tweets: print(f"{tweet.created_at} - {tweet.text}\n")
按道理OAuth1.0验证可以通过,但是被403禁止拦截了,OAuth2.0又有点麻烦,所以想绕过这两个方式。
构造请求应该为:
GET https://api.twitter.com/1.1/favorites/list.json?count=200&screen_name=twitterdev
随即会返回一个json内容块,读取json即可,因此,我们可以构造一个例子:
# 设置 API 请求参数,注意参数之间没有空格,不然报错
params = {
'user.fields': 'name,public_metrics,description,created_at',
}
# 设置请求头,添加 Bearer 令牌
headers = {
'Authorization': f'Bearer {beartoken}',
'Content-Type': 'application/json',
}
这里的params参数可以在开发者文档(https://developer.twitter.com/en/docs/twitter-api/users/lookup/quick-start/user-lookup)中查阅:
随后发送用re发送请求,这里挑选了一个查找用户的接口,按照文档构造请求:
response = requests.get(f'https://api.twitter.com/2/users/by/username/{username}', params=params, headers=headers)
得到的response就是文档中提到的json内容:
# 处理响应
if response.status_code == 200:
json_response = response.json()
t = json_response["data"]['created_at']
json_response["data"]['created_at'] = convert_utc_to_china(t, format="%Y年%m月%d日")
print(json_response)
else:
raise Exception(f"Request returned an error: {response.status_code} {response.text}")
def remove_links(tweet_text): # 使用正则表达式匹配链接的模式 link_pattern = r'https?://\S+|www\.\S+' # 使用 sub 方法替换链接为空字符串 cleaned_text = re.sub(link_pattern, '', tweet_text) cleaned_text = cleaned_text.replace('\n\n', '\n') return cleaned_text def get_tweet_info(tweet_url, beartoken=beartoken): # 从推文链接中截取推文ID tweet_id = tweet_url.split('/')[-1].split('?')[0] # 设置 API 请求参数 params = { 'ids': tweet_id, # 'tweet.fields': 'created_at,public_metrics,text.extended', 'tweet.fields': 'created_at,note_tweet,public_metrics', # [attachments,author_id,context_annotations,conversation_id,created_at,edit_controls,edit_history_tweet_ids, # entities,geo,id,in_reply_to_user_id,lang,non_public_metrics,note_tweet,organic_metrics,possibly_sensitive, # promoted_metrics,public_metrics,referenced_tweets,reply_settings,source,text,withheld] } # 设置请求头,添加 Bearer 令牌 headers = { 'Authorization': f'Bearer {beartoken}', 'Content-Type': 'application/json', } # 发送请求 response = requests.get('https://api.twitter.com/2/tweets', params=params, headers=headers) # 处理响应 if response.status_code == 200: json_response = response.json() # 将Unicode编码转换成中文编码 # print(json.dumps(json_response, indent=4)) text = json_response['data'][0]['text'] if 'note_tweet' in json_response['data'][0].keys(): # print(json_response['data'][0].keys()) note_tweet = json_response['data'][0]['note_tweet']['text'] text = note_tweet else: note_tweet = json_response['data'][0]['text'] text = remove_links(text) json_response['data'][0]['text'] = text # tweet_text = json.loads(f'"{text}"') t = json_response['data'][0]['created_at'] china_t = convert_utc_to_china(t) json_response['data'][0]['created_at'] = china_t return json_response else: raise Exception(f"Request returned an error: {response.status_code} {response.text}")
重新更新berar-token,修改进去就行了,我个人认为应该是请求次数过多,导致把个人应用的秘钥暂时禁用了。
添加note_tweet参数,可以返回长文本,text做不到返回长文本
# 设置 API 请求参数
params = {
'ids': tweet_id,
'tweet.fields': 'created_at,public_metrics,note_tweet',
# [attachments,author_id,context_annotations,conversation_id,created_at,edit_controls,edit_history_tweet_ids,
# entities,geo,id,in_reply_to_user_id,lang,non_public_metrics,note_tweet,organic_metrics,possibly_sensitive,
# promoted_metrics,public_metrics,referenced_tweets,reply_settings,source,text,withheld]
}
请求api次数过多,等一会再发送请求就可以了。
# 设置点击时间记录 CLICK_TIMES = [] CLICK_LIMIT = CFG['CLICK_LIMIT'] # 请求函数。。。。。 global CLICK_TIMES time_now = datetime.now() if len(CLICK_TIMES) == CLICK_LIMIT: # 循环更新队列, 只储存一分钟之内的5次请求时间,其他时间去掉 for t in CLICK_TIMES: if minutes_1(CLICK_TIMES[-1], t) or minutes_1(time_now, t): CLICK_TIMES.remove(t) else: break if len(CLICK_TIMES) < CLICK_LIMIT: CLICK_TIMES.append(time_now) print(f"get_limit = {CLICK_TIMES}") else: days, hours, minutes, seconds = calculate_time_click(time_now, CLICK_TIMES[0]) # 当点击的5次请求都在一分钟之内,再次点击,此时报错 messagebox.showerror("错误!", f"点击次数过多, 请{60 - seconds}秒后重试") return
创建
重新创建项目,项目被自动支付失败关闭。重新创建项目和子app
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。