【问题标题】:python, tweepy: urllib2.HTTPError: HTTP Error 403: Forbiddenpython,tweepy:urllib2.HTTPError:HTTP错误403:禁止
【发布时间】:2013-12-30 19:54:14
【问题描述】:

我正在编写一个 Twitter 应用程序并尝试使用 tweepy 进行授权。 我收到以下错误,不知道为什么..

谁能帮帮我?我将不胜感激。

Traceback (most recent call last):
File "getconv.py", line 32, in <module>
auth=AppAuthHandler(consumer_token,consumer_secret)
File "getconv.py", line 25, in __init__
response=urllib2.urlopen(req,data)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 400, in open
response = meth(req, response)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 513, in http_response
'http', request, response, code, msg, hdrs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 432, in error
result = self._call_chain(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 372, in _call_chain
result = func(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 619, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 400, in open
response = meth(req, response)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 513, in http_response
'http', request, response, code, msg, hdrs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 438, in error
return self._call_chain(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 372, in _call_chain
result = func(*args)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 521, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden

以下是我的代码

import urllib2
import time
import sys
import tweepy
import base64
import urllib
#import twitter

consumer_token='my consumer token'
consumer_secret='my consumer secret'
access_token='my access token'
access_secret='my access secret'

class AppAuthHandler(tweepy.auth.AuthHandler):
    TOKEN_URL='http://api.twitter.com/oauth2/token'

    def __init__(self,consumer_key,consumer_secret):
            token_credential=urllib.quote(consumer_key)+':'+urllib.quote(consumer_secret)
            credential=base64.b64encode(token_credential)
            value={'grant_type':'client_credentials'}
            data=urllib.urlencode(value)
            req=urllib2.Request(self.TOKEN_URL)
            req.add_header('Authorization','Basic'+credential)
            req.add_header('Content_Type','application/x-www-form-urlencoded;charset=UTF-8')
            response=urllib2.urlopen(req,data)
            json_response=json.loads(response.read())
            self._access_token=json_response['access_token']

    def apply_auth(self,url,method,headers,parameters):
            headers['Authorization']='Bearer'+self._access_token

auth=AppAuthHandler(consumer_token,consumer_secret)
oauth_api=tweepy.API(auth)

【问题讨论】:

  • 您的问题标题有点误导,因为(假设您的身份验证信息正确)它似乎是 tweepy 的问题。另一方面,您的 Header 意味着直接使用 urllib2 存在问题
  • @AndreasKlebinger 我现在不能确定错误是来自 urllib2 还是 tweepy。无论如何,我在标题上添加了 tweepy。

标签: python python-2.7 twitter tweepy http-error


【解决方案1】:

该错误与tweepy无关,来自您自定义的AppAuthHandler

>>> auth = AppAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden

您的代码中实际上存在 三个错误:

  • 链接应使用https 而不是http
  • Content-Type 标头的名称使用破折号而不是下划线
  • Authorization 标头必须在 Basic 和凭据之间保留一个空格,添加它。

我为您的代码提供包含修复以供参考(没有改进,仅修复):

class AppAuthHandler(tweepy.auth.AuthHandler):
    TOKEN_URL='https://api.twitter.com/oauth2/token'
    def __init__(self,consumer_key,consumer_secret):
        token_credential = '{}:{}'.format(*map(urllib.quote, [consumer_key, consumer_secret]))
        credential = base64.b64encode(token_credential)
        value = {'grant_type': 'client_credentials'}
        data = urllib.urlencode(value)
        req = urllib2.Request(self.TOKEN_URL)
        req.add_header('Authorization', 'Basic {}'.format(credential))
        req.add_header('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8')
        response=urllib2.urlopen(req, data)
        json_response=json.loads(response.read())
        self._access_token=json_response['access_token']
    def apply_auth(self,url,method,headers,parameters):
        headers['Authorization'] = 'Bearer {}'.format(self._access_token)

演示:

>>> AppAuthHandler(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET)
<__main__.AppAuthHandler object at 0x11b7d10>

【讨论】:

  • 非常感谢您的回答。现在在您的帮助下,代码本身可以工作,但我仍然得到错误的身份验证数据:代码 215 错误。身份验证后,我通过 url = "api.twitter.com/1.1/search/show.json?id="+tweetid 调用 url,然后 tweetdata=urllib2.urlopen(url).read( ) 你能帮我找出原因吗?
  • @CosmicRabbitMediaInc 出于好奇,为什么不api = tweepy.API(auth)api.&lt;some_method&gt;?你认为"api.twitter.com/1.1/search/show.json?id= 是什么端点?它是 1.0 的链接吗?
  • 我不确定您所说的 是什么意思.. 上面 url 的结果只是 "{"errors":[{"message":"Bad Authentication data","code": 215}]}" 没有参考 1.0
猜你喜欢
  • 2012-10-14
  • 2021-11-22
  • 2023-03-12
  • 2012-10-29
  • 2021-06-02
  • 2022-01-18
  • 2020-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多