Twitter HTTP 请求:403 错误

Twitter HTTP Requests: 403 error

我想在 Python 中向 Twitter 发送一些 HTTP 请求,以便为我的应用程序的 Twitter 用户创建登录。我正在使用 urllib,并遵循此 link: 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

如果您使用浏览器访问 url,它会显示您需要一个密钥:

Whoa there! There is no request token for this page. That's the special key we need from applications asking to use your Twitter account. Please go back to the site or application that sent you here and try again; it was probably just a mistake.

如果您转到 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]