Twitter HTTP请求:403错误

时间:2015-04-18 11:15:41

标签: python twitter urllib

我想在Python中向Twitter发送一些HTTP请求,以便为我的应用创建Twitter用户的登录。我正在使用urllib,并点击此链接:https://dev.twitter.com/web/sign-in/implementing

但我无法做到这一点。我想我需要在请求令牌之前进行身份验证,但我不知道该怎么做。

代码:

import urllib.request
req = urllib.request.Request("https://api.twitter.com/oauth/authenticate",
headers={'User-Agent': 'Mozilla/5.0'})
html = urllib.request.urlopen(req).read()   //after this statement im 
                                              getting the error

错误:

Traceback (most recent call last):
    File "<pyshell#5>", line 1, in <module>
     html = urllib.request.urlopen(req).read()
    File "C:\Python34\lib\urllib\request.py", line 161, in urlopen
      return opener.open(url, data, timeout)
    File "C:\Python34\lib\urllib\request.py", line 469, in open
      response = meth(req, response)
    File "C:\Python34\lib\urllib\request.py", line 579, in http_response
      'http', request, response, code, msg, hdrs)
    File "C:\Python34\lib\urllib\request.py", line 507, in error
     return self._call_chain(*args)
    File "C:\Python34\lib\urllib\request.py", line 441, in _call_chain
     result = func(*args)
    File "C:\Python34\lib\urllib\request.py", line 587, in http_error_default
     raise HTTPError(req.full_url, code, msg, hdrs, fp)
    urllib.error.HTTPError: HTTP Error 403: Forbidden

1 个答案:

答案 0 :(得分:1)

如果您使用浏览器访问该网址,则会显示您需要密钥:

  

哇那里!   此页面没有请求令牌。这是我们要求使用您的Twitter帐户的应用程序所需的特殊密钥。请返回发送给您的网站或应用程序,然后重试;这可能只是一个错误。

如果你转到this link,它会让你选择一个应用程序和 它会带你到一个签名生成器,它将显示请求设置。

要获取request_token,您可以使用requests_oauthlib

import requests
from requests_oauthlib import OAuth1


REQUEST_TOKEN_URL = "https://api.twitter.com/oauth/request_token"
CONSUMER_KEY = "xxxxxxxx
CONSUMER_SECRET = "xxxxxxxxxxxxxxxxx"

oauth = OAuth1(CONSUMER_KEY, client_secret=CONSUMER_SECRET)
r = requests.post(url=REQUEST_TOKEN_URL, auth=oauth)
print(r.content)
oauth_token=xxxxxxxxxxxxxx&oauth_token_secret=xxxxxxxxxxx&oauth_callback_confirmed=true

然后你需要提取oauth_token oauth_token_secret:

from urlparse import parse_qs
import webbrowser

data = parse_qs(r.content)
oauth_token = data['oauth_token'][0]
oauth_token_secret = data['oauth_token_secret'][0]
AUTH = "https://api.twitter.com/oauth/authorize?oauth_token={}"
auth = AUTH.format(oauth_token)
webbrowser.open(auth)

网页会打开,要求授权your_app使用您的帐户吗?

对于python 3使用:

from urllib.parse import parse_qs


data = parse_qs(r.text)
oauth_token = data['oauth_token'][0]
oauth_token_secret = data['oauth_token_secret'][0]