处理 Python-requests请求的超时时间

python程序根据url从互联网上批量下载图片时,设置HTTP或Socket超时,来防止爬虫爬取某个页面时间过长,导致程序卡置不前。我之前开发的一个脚本读取kafka 就是拿图片 后续一直卡在这里。

一种解决方案是全局设置:

import socket
socket.setdefaulttimeout(t)
t:代表经过t秒后,如果还未下载成功,自动跳入下一次操作,此次下载失败

另外一种解决方案是:

使用timeout 参数可以设定等待连接的数,如果等待超时,Requests会抛出异常

>>> requests.get('http://github.com', timeout=0.001)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
>>> requests.get('https://www.baidu.com',timeout=0.5)
<Response [200]>

timeout 仅对连接过程有效,与响应体的下载无关。 timeout 并不是整个下载响应的时间限制,而是如果服务器在 timeout 秒内没有应答,将会引发一个异常(更精确地说,是在 timeout 秒内没有从基础套接字上接收到任何字节的数据时)。

第三种

import time
import requests
from requests.adapters import HTTPAdapter
s = requests.Session()
s.mount('http://', HTTPAdapter(max_retries=3))
s.mount('https://', HTTPAdapter(max_retries=3))
print(time.strftime('%Y-%m-%d %H:%M:%S'))
try:
    r = s.get('http://www.google.com.hk', timeout=5)
    return r.text
except requests.exceptions.RequestException as e:
    print(e)
print(time.strftime('%Y-%m-%d %H:%M:%S'))

max_retries 为最大重试次数,重试3次,加上最初的一次请求,一共是4次,所以上述代码运行耗时是20秒而不是15秒

 

第四种:捕获请求异常:

def gethtml(url):
    i = 0
    while i < 3:
    try:
        html = requests.get(url, timeout=5).text
        return html
    except requests.exceptions.RequestException:
      i += 1
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java的世界里,HttpClient 是一个功能强大的Http请求库,然而接口非常复杂,设计上遵从正交性,简单的请求也需要写比较多的代码,更不要说隐藏在各种细节里面的高级用法了。Requests,  是一个模仿python requests 模块来设计的Http lib,拥有简单而灵活的API,在容易使用的同时,又能够满足各种高级定制的使用,可是说是当前最好用的Java Http Client Lib。 简单的请求示例:String url = ...; Response resp = Requests.get(url).text(); // post 和其他方法 resp = Requests.post(url).text(); resp = Requests.head(url).text(); //读取Http Response  int statusCode = resp.getStatusCode(); Headers headers = resp.getHeaders(); Cookies cookies = resp.getCookies(); String body = resp.getBody(); //response 返回其他类型 resp = Requests.get(url).text("UTF-8"); // get response as bytes Response resp1 = Requests.get(url).bytes(); // save response as file  Response resp2 = Requests.get(url).file("/path/to/save/file"); // url 参数: Map map = new HashMap(); map.put("k1", "v1"); map.put("k2", "v2"); Response resp = Requests.get(url).param("key1", "value1").params(map)         //.params(new Parameter(...), new Parameter(...))         .text(); // 请求头 Response resp = Requests.get(url).header("key1", "value1").headers(map)         //.headers(new Header(...), new Header(...))         .text(); // 添加Cookie: Map cookies = new HashMap(); Response resp = Requests.get(url).cookie("key1", "value1").cookies(map)         //.cookies(new Cookie(...), new Cookie(...))         .text(); //  设置 userAgent Response resp = Requests.get(url).userAgent(userAgent).text(); // 增加请求数据(post, put, patch方法) // send form-encoded data. x-www-form-urlencoded header will be send automatically Response resp = Requests.post(url).data(map).text(); // send string data String str = ...; resp = Requests.post(url).data(str, "UTF-8").text(); // send from inputStream InputStream in = ... resp = Requests.post(url).data(in).text(); // multipart 请求, 用于文件上传: Response resp = Requests.post(url).data(map).multiPart("ufile", "/path/to/file")         .multiPart(..., ...).text();请求设置://禁止自动重定向

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值