python requests.get 用代理就超时_为什么requests.get()不返回?requests.get()使用的默认超时是什么?...

You can tell Requests to stop waiting for a response after a given

number of seconds with the timeout parameter:>>> requests.get('http://github.com', timeout=0.001)

Traceback (most recent call last):

File "", line 1, in

requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

Note:

timeout is not a time limit on the entire response download; rather,

an exception is raised if the server has not issued a response for

timeout seconds (more precisely, if no bytes have been received on the

underlying socket for timeout seconds).

在我看来,requests.get()需要很长时间才能返回,即使timeout是1秒。有几种方法可以克服这个问题:

1。使用内部类TimeoutSauceimport requests from requests.adapters import TimeoutSauce

class MyTimeout(TimeoutSauce):

def __init__(self, *args, **kwargs):

if kwargs['connect'] is None:

kwargs['connect'] = 5

if kwargs['read'] is None:

kwargs['read'] = 5

super(MyTimeout, self).__init__(*args, **kwargs)

requests.adapters.TimeoutSauce = MyTimeout

This code should cause us to set the read timeout as equal to the

connect timeout, which is the timeout value you pass on your

Session.get() call. (Note that I haven't actually tested this code, so

it may need some quick debugging, I just wrote it straight into the

GitHub window.)If you specify a single value for the timeout, like this:r = requests.get('https://github.com', timeout=5)

The timeout value will be applied to both the connect and the read

timeouts. Specify a tuple if you would like to set the values

separately:r = requests.get('https://github.com', timeout=(3.05, 27))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值