urllib.request.urlopen与身份验证实现问题

时间:2018-11-21 17:13:54

标签: python urllib

我正在尝试访问提供JSON的API,并且此api需要身份验证。到目前为止,我已经研究了https://docs.python.org/3.1/howto/urllib2.html#id6,并且在尝试实施时遇到了一些疑问

首先,我要获得此回溯

Traceback (most recent call last):
  File "test.py", line 17, in <module>
    opener.open("<API URL>")
  File "/usr/lib64/python3.6/urllib/request.py", line 532, in open
    response = meth(req, response)
  File "/usr/lib64/python3.6/urllib/request.py", line 642, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib64/python3.6/urllib/request.py", line 570, in error
    return self._call_chain(*args)
  File "/usr/lib64/python3.6/urllib/request.py", line 504, in _call_chain
    result = func(*args)
  File "/usr/lib64/python3.6/urllib/request.py", line 650, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 400: 

这是我正在运行的test.py文件(并在其中添加了评论)

import urllib.request, json 

# create a password manager

password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.

top_level_url = "<URL where authentication form is requested>"
password_mgr.add_password(None, top_level_url, "<username>", "<password>")

handler = urllib.request.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)

opener = urllib.request.build_opener(handler)

# use the opener to fetch a URL

opener.open("<API URL>")

# Install the opener.
# Now all calls to urllib.request.urlopen use our opener.

urllib.request.install_opener(opener)

# Code to print JSON from API url

with urllib.request.urlopen("<API URL>") as url:
    data = json.loads(url.read().decode())
    print(data)

有些不清楚的地方:

opener.open处使用的URL是存在API而不是顶层的URL,对吗?

当我尝试使用data时以with urllib.request.urlopen("<API URL>") as url:的形式返回JSON时,当“对urllib.request.urlopen的所有调用都使用我们的打开器”时,我应该放置<API URL>吗?这是否意味着我不必将任何内容传递给urlopen?或也许通过开瓶器?

0 个答案:

没有答案
相关问题