python 3, window 7 :ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

标签 python json url python-3.x

已编辑:

我使用企业环境,在我的家庭环境中脚本运行正常

我正在尝试从某些天气网站获得响应。我制作了一个简单的 python 脚本。

import urllib.request
import json

req=urllib.request.Request("http://api.wunderground.com/api/e0b319c6f7e8115a/geolookup/conditions/q/IA/Cedar_Rapids.json")
 response=urllib.request.urlopen(req)
 data = json.loads(response.read().decode())  #<--according to @falsetru fix
 print (data)

当我将 URL 粘贴到浏览器时,我得到响应,但在 python 中我得到错误 请帮忙

完全错误

Traceback (most recent call last):
File "C:\Python34\weather.py", line 14, in <module>
response=urllib.request.urlopen(req)
File "C:\Python34\lib\urllib\request.py", line 153, in urlopen
return opener.open(url, data, timeout)
File "C:\Python34\lib\urllib\request.py", line 455, in open
response = self._open(req, data)
File "C:\Python34\lib\urllib\request.py", line 473, in _open
'_open', req)
File "C:\Python34\lib\urllib\request.py", line 433, in _call_chain
result = func(*args)
File "C:\Python34\lib\urllib\request.py", line 1202, in http_open
return self.do_open(http.client.HTTPConnection, req)
File "C:\Python34\lib\urllib\request.py", line 1177, in do_open
r = h.getresponse()
File "C:\Python34\lib\http\client.py", line 1172, in getresponse
response.begin()
File "C:\Python34\lib\http\client.py", line 351, in begin
version, status, reason = self._read_status()
File "C:\Python34\lib\http\client.py", line 313, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "C:\Python34\lib\socket.py", line 371, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

谢谢

最佳答案

您的代码按预期工作,除了应解码响应字节,因为 json.loads需要一个 str 对象。

更新

需要像浏览器一样在Python代码中配置代理。您可以使用 urllib.request.Request.set_proxy , 或 urllib.request.ProxyHandler :


import urllib.request
import json

req = urllib.request.Request("http://api.wunderground.com/api/e0b319c6f7e8115a/geolookup/conditions/q/IA/Cedar_Rapids.json")
req.set_proxy('PROXY_HOST:PROXY_PORT', 'http')  # <---
response = urllib.request.urlopen(req)
data = json.loads(response.read().decode())  # <----
print(data)

关于 python 3, window 7 :ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27732075/

相关文章:

python - 使用 Python 将一个文本文件逐行复制到另一个文本文件

python - 线程错误 : AttributeError: 'NoneType' object has no attribute '_initialized'

json - 类型 any 没有下标成员 swift 3

html - 我如何告诉谷歌我已经从我的网址中删除了 .html?

python - 根据变量名称将列添加到数据框

python - 获取用Python Zelle图形绘制的图形的坐标颜色

javascript - 在javascript中从json中提取值

php - jQuery | Ajax,如何从外部 PHP 文件中接收的数据中操作数组键?

java.net.ConnectException : Connection timed out while connecting through a proxy 异常

linux - 使用 jboss 7.1 将图像显示为 url