因此,我想简单地使用以下命令读取网站的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还有一些类似的问题,但对我来说解决方案不起作用。
发布于 2021-11-20 17:13:29
我能够重现这种行为。
可以通过使用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())我认为这是因为HTML服务器已经被设置为阻止带有与https://dictionary.cambridge.org's抓取相关的头的请求(就像urllib.request.urlopen的默认头一样)。
然而,我不确定故意使用不正确的报头是否符合道德规范;它们可能会因为某种原因而被阻止……
https://stackoverflow.com/questions/70047924
复制相似问题