[英]Python web scraping: difference between sleep and request(page, timeout=x)
[英]define timeout in web request with python
这是我的情况。 在某些情况下,我向网页发出请求的时间过长。 我希望当它花费超过10秒而不从服务器发出响应时,该请求将被取消,但不会收到任何错误。 这是我当前的代码,并显示给我错误。 当出现此错误时,我的代码结束。 总而言之,我想提出一个Web请求,并限制如果10秒钟内没有答案,我将完成请求并继续执行我的代码。
requests.post("www.webpage.com", headers = {'Content-type': 'application/x-www-form-urlencoded'}, data = {"conid":1,"event":5},timeout=10)
.
.
.
经过10秒后,我收到此错误
ReadTimeout: HTTPConnectionPool(host='www.webpage.com', port=80): Read timed out. (read timeout=10)
出于机密性原因,我不会放置真实的url,但是通常不设置超时就可以了
使用exception
来处理超时
try:
requests.post("www.webpage.com", headers = {'Content-type': 'application/x-www-form-urlencoded'}, data = {"conid":1,"event":5},timeout=10)
except requests.exceptions.ReadTimeout:
print("Server didn't respond within 10 seconds")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.