【问题标题】:Getting "RemoteDisconnected" Error using urlopen使用 urlopen 出现“RemoteDisconnected”错误
【发布时间】:2021-12-31 00:00:20
【问题描述】:

所以我想简单地阅读网站的 Html 使用

from urllib.request import urlopen
url = 'https://dictionary.cambridge.org/dictionary/english/water'
page = urlopen(url)

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

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

有一些类似的问题,但没有对我有用的解决方案。

【问题讨论】:

    标签: python python-3.x urlopen


    【解决方案1】:

    我能够重现这种行为。

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

    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())
    

    我建议发生这种情况,因为 https://dictionary.cambridge.org 的网络服务器已设置为阻止带有与 HTML 抓取相关联的标头的请求(例如 urllib.request.urlopen 的默认标头)。

    但是,我不确定故意使用错误标题的道德规范;他们可能因某种原因被阻止...

    【讨论】:

    • 感谢您的回答。该解决方案对我有用,但我不确定您是否编写了 sn-p 代码。请编辑您的代码,以便我接受您的回答。
    • @mike 你不确定什么?我很乐意澄清任何事情。
    • 为什么要导入请求s(第 2 行)。这不是拼写错误吗?
    • @mike 这不是错字,如果你不导入它,你会得到一个AttributeError,因为Requestrequests 的一部分而不是urllib。实际上,您可以仅使用 requests 模块获取 HTML 文件,但由于在您的问题中您使用的是 urllib,因此我也使用了它。
    猜你喜欢
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 2017-11-21
    • 2020-03-04
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    相关资源
    最近更新 更多