首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用urlopen获取"RemoteDisconnected“错误

使用urlopen获取"RemoteDisconnected“错误
EN

Stack Overflow用户
提问于 2021-11-20 16:45:34
回答 1查看 40关注 0票数 1

因此,我想简单地使用以下命令读取网站的Html

代码语言:javascript
复制
from urllib.request import urlopen
url = 'https://dictionary.cambridge.org/dictionary/english/water'
page = urlopen(url)

对于一些网站,它可以工作,但对于上面代码中的一些网站,我得到了错误

代码语言:javascript
复制
Traceback (most recent call last):
  File "F:/mohammad Desktop/work spaces/python/Python Turial Release 3.9.1/mod2.py", line 4, in <module>
    page = urlopen(url)
  File "C:\Python\Python38\lib\urllib\request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python\Python38\lib\urllib\request.py", line 525, in open
    response = self._open(req, data)
  File "C:\Python\Python38\lib\urllib\request.py", line 542, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
  File "C:\Python\Python38\lib\urllib\request.py", line 502, in _call_chain
    result = func(*args)
  File "C:\Python\Python38\lib\urllib\request.py", line 1362, in https_open
    return self.do_open(http.client.HTTPSConnection, req,
  File "C:\Python\Python38\lib\urllib\request.py", line 1323, in do_open
    r = h.getresponse()
  File "C:\Python\Python38\lib\http\client.py", line 1322, in getresponse
    response.begin()
  File "C:\Python\Python38\lib\http\client.py", line 303, in begin
    version, status, reason = self._read_status()
  File "C:\Python\Python38\lib\http\client.py", line 272, in _read_status
    raise RemoteDisconnected("Remote end closed connection without"
http.client.RemoteDisconnected: Remote end closed connection without response

还有一些类似的问题,但对我来说解决方案不起作用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-20 17:13:29

我能够重现这种行为。

可以通过使用request对象并将请求标头更改为通常在web浏览器中使用的标头来解决此问题。例如,mac上的firefox:

代码语言:javascript
复制
import urllib
import requests

url = 'https://dictionary.cambridge.org/dictionary/english/water'

req = urllib.request.Request(url, headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_5_8) AppleWebKit/534.50.2 (KHTML, like Gecko) Version/5.0.6 Safari/533.22.3'})
print(urllib.request.urlopen(req).read())

我认为这是因为HTML服务器已经被设置为阻止带有与https://dictionary.cambridge.org's抓取相关的头的请求(就像urllib.request.urlopen的默认头一样)。

然而,我不确定故意使用不正确的报头是否符合道德规范;它们可能会因为某种原因而被阻止……

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70047924

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档