我执行了这段代码以连接最常见的api-
import requests
response = requests.get("http://api.open-notify.org/iss-now.json")
print(response.status_code)
但它显示此错误-
runfile('C:/Users/sanchit.joshi/use case of unassigned tickets/Api try
out.py', wdir='C:/Users/sanchit.joshi/use case of unassigned tickets')
Traceback (most recent call last):
File "<ipython-input-17-39bcdc5917ae>", line 1, in <module>
runfile('C:/Users/sanchit.joshi/use case of unassigned tickets/Api try
out.py', wdir='C:/Users/sanchit.joshi/use case of unassigned tickets')
File "C:\ProgramData\Anaconda3\lib\site-
packages\spyder_kernels\customize\spydercustomize.py", line 668, in
runfile
execfile(filename, namespace)
File "C:\ProgramData\Anaconda3\lib\site-
packages\spyder_kernels\customize\spydercustomize.py", line 108, in
execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/sanchit.joshi/use case of unassigned tickets/Api try
out.py", line 8, in <module>
response = requests.get("http://api.open-notify.org/iss-now.json")
File "C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py", line
72, in get
return request('get', url, params=params, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py", line
58, in request
return session.request(method=method, url=url, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py",
line 512, in request
resp = self.send(prep, **send_kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py",
line 622, in send
r = adapter.send(request, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py",
line 513, in send
raise ConnectionError(e, request=request)
ConnectionError: HTTPConnectionPool(host='api.open-notify.org',
port=80): Max retries exceeded with url: /iss-now.json (Caused by
NewConnectionError('<urllib3.connection.HTTPConnection object at
0x000001E8E5BCBE80>: Failed to establish a new connection: [Errno 11002]
getaddrinfo failed'))
我尝试更改最大重试值,但不起作用。更令人沮丧的是,这是连接到api的最简单代码。任何帮助表示赞赏。
答案 0 :(得分:0)
import json
import urllib.request
file = urllib.request.urlopen("http://api.open-notify.org/iss-now.json")
data = json.loads(file.read())
print(data)
产生
{'message': 'success', 'timestamp': 1541059187, 'iss_position': {'longitude': '13.6813', 'latitude': '47.8641'}}
答案 1 :(得分:0)
您的代码没有错,该代码应该可以工作。
您遇到代理问题。如果您在Windows上,则可以通过以下步骤将URL添加到代理例外中:Internet浏览器中的设置菜单,然后依次选择Internet选项,连接,局域网设置,并将URL添加到例外中。在公司环境或您的学校中,管理员通常会把您置于代理之后。
或者,您可以使用this Q/A在请求中设置代理