python请求超时。获取整个响应

2024-04-20 01:58:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在收集一个网站列表上的统计数据,为了简单起见,我正在使用它的请求。这是我的代码:

data=[]
websites=['http://google.com', 'http://bbc.co.uk']
for w in websites:
    r= requests.get(w, verify=False)
    data.append( (r.url, len(r.content), r.elapsed.total_seconds(), str([(l.status_code, l.url) for l in r.history]), str(r.headers.items()), str(r.cookies.items())) )

现在,我希望requests.get在10秒后超时,这样循环就不会卡住。

这个问题也很有趣,但没有一个答案是清楚的。我会给你一些赏金来得到一个好的答案。

我听说也许不使用请求是个好主意,但是我应该如何得到请求提供的好东西。(元组中的那个)


Tags: 答案代码inhttpurl列表fordata
3条回答

使用eventlet怎么样?如果您希望在10秒后超时请求,即使正在接收数据,此代码段也将适用于您:

import requests
import eventlet
eventlet.monkey_patch()

with eventlet.Timeout(10):
    requests.get("http://ipv4.download.thinkbroadband.com/1GB.zip", verify=False)

设置timeout parameter

r = requests.get(w, verify=False, timeout=10) # 10 seconds

只要您没有对该请求设置stream=True,如果连接时间超过10秒,或者服务器发送数据的时间超过10秒,则会导致对requests.get()的调用超时。

更新:http://docs.python-requests.org/en/master/user/advanced/#timeouts

在新版requests中:

如果为超时指定一个值,如下所示:

r = requests.get('https://github.com', timeout=5)

超时值将同时应用于connectread超时。如果要分别设置值,请指定元组:

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

如果远程服务器非常慢,可以告诉请求永远等待响应,方法是将None作为超时值传递,然后检索一杯咖啡。

r = requests.get('https://github.com', timeout=None)

我旧的(可能过时的)答案(很久以前就贴出来了):

有其他方法可以克服这个问题:

1。使用内部类TimeoutSauce

发件人:https://github.com/kennethreitz/requests/issues/1928#issuecomment-35811896

import requests from requests.adapters import TimeoutSauce

class MyTimeout(TimeoutSauce):
    def __init__(self, *args, **kwargs):
        connect = kwargs.get('connect', 5)
        read = kwargs.get('read', connect)
        super(MyTimeout, self).__init__(connect=connect, read=read)

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.)

2。使用来自kevinburke的请求分支:https://github.com/kevinburke/requests/tree/connect-timeout

从它的文档中:https://github.com/kevinburke/requests/blob/connect-timeout/docs/user/advanced.rst

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))

kevinburke has requested它将被合并到主请求项目中,但尚未被接受。

相关问题 更多 >