我正在使用请求库从某处获取大量网页。他是相关代码:
response = requests.Session()
retries = Retry(total=5, backoff_factor=.1)
response.mount('http://', HTTPAdapter(max_retries=retries))
response = response.get(url)
一段时间后,它在获取页面时只是挂起/冻结(从不在同一网页上)。这是我中断它时的回溯:
File "/Users/Student/Hockey/Scrape/html_pbp.py", line 21, in get_pbp
response = r.read().decode('utf-8')
File "/anaconda/lib/python3.6/http/client.py", line 456, in read
return self._readall_chunked()
File "/anaconda/lib/python3.6/http/client.py", line 566, in _readall_chunked
value.append(self._safe_read(chunk_left))
File "/anaconda/lib/python3.6/http/client.py", line 612, in _safe_read
chunk = self.fp.read(min(amt, MAXAMOUNT))
File "/anaconda/lib/python3.6/socket.py", line 586, in readinto
return self._sock.recv_into(b)
KeyboardInterrupt
有人知道是什么原因造成的吗?或者(更重要的是)如果需要超过一定时间,有人知道阻止它的方法以便我可以重试吗?
原文由 Hobbit36 发布,翻译遵循 CC BY-SA 4.0 许可协议
似乎设置(读取) 超时 可能对您有所帮助。
类似的东西:
(这会将连接和读取超时设置为 5 秒。)
在
requests
中,不幸的是,默认情况下既没有设置 连接 超时也没有设置 读取 超时,即使 文档 说设置它很好:只是为了完整起见, 连接超时 是秒数
requests
将等待您的客户端与远程计算机建立连接, 读取超时 是客户端从发送的字节之间等待的秒数服务器。