使用requests_oauthlib访问OAuth2网页

时间:2016-11-20 23:36:27

标签: python-2.7 oauth-2.0 python-requests

一直在关注使用RequestsBeautifulSoup4进行网页抓取的教程。我正在尝试从www.showmyhomework.com网站访问信息,但我认为该网站正在使用OAuth2授权。遗憾的是,本教程未介绍如何使用OAuth2的页面执行此操作。花了几个小时阅读OAuth2文档,但无法弄清楚我如何让我的Python脚本请求令牌并访问网页。下面的python脚本来自OAuth2文档,但我显然做错了什么!

from oauthlib.oauth2 import LegacyApplicationClient
from requests_oauthlib import OAuth2Session

client_Id = 'My_Google_supplied_OAuth2_Client_Id.apps.googleusercontent.com'
client_Secret = 'My_Google_supplied OAuth Client_Secret'
redirect_uri = 'https://your.callback/uri'

oauth = OAuth2Session(client=LegacyApplicationClient(client_id=client_Id))
token = oauth.fetch_token(token_url='https://www.showmyhomework.com/oauth2/token',
            username="My_Username", password="My_Password", client_id=client_Id,
            client_secret=client_Secret)
print(token)

我在回复时收到了这些错误:

=================== RESTART: E:/Programs/Python27/Auth.py ===================

Traceback (most recent call last):
  File "E:/Programs/Python27/Auth.py", line 11, in <module>
    client_secret=client_Secret)
  File "E:\Programs\Python27\lib\site-packages\requests_oauthlib\oauth2_session.py", line 244, in fetch_token
    self._client.parse_request_body_response(r.text, scope=self.scope)
  File "E:\Programs\Python27\lib\site-packages\oauthlib\oauth2\rfc6749\clients\base.py", line 409, in parse_request_body_response
    self.token = parse_token_response(body, scope=scope)
  File "E:\Programs\Python27\lib\site-packages\oauthlib\oauth2\rfc6749\parameters.py", line 376, in parse_token_response
    validate_token_parameters(params)
  File "E:\Programs\Python27\lib\site-packages\oauthlib\oauth2\rfc6749\parameters.py", line 386, in validate_token_parameters
    raise MissingTokenError(description="Missing access token parameter.")
MissingTokenError: (missing_token) Missing access token parameter. 

1 个答案:

答案 0 :(得分:1)

我遇到了同样的问题,我通过在auth=False中添加fetch_token来解决此问题。

 oauth = OAuth2Session(client=LegacyApplicationClient(client_id=client_Id))
 token = oauth.fetch_token(token_url='https://www.showmyhomework.com/oauth2/token',
        username="My_Username", password="My_Password", client_id=client_Id,
        client_secret=client_Secret, auth=False)
祝你好运。