设置urllib2.request()的超时

2024-03-28 13:40:31 发布

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

我需要在urllib2.request()上设置超时。

我不使用urllib2.urlopen(),因为我使用requestdata参数。我怎么设置这个?


Tags: data参数requesturllib2urlopen
3条回答

不过,您仍然可以避免使用urlopen,并按如下方式继续:

request = urllib2.Request('http://example.com')
response = opener.open(request,timeout=4)
response_result = response.read()

这也管用:)

为什么不使用可怕的requests?你会节省很多时间的。

如果您担心部署,请将其复制到项目中。

请求的例子:

>>> requests.post('http://github.com', data={your data here}, timeout=10)

尽管urlopen确实接受data的参数,但您可以对这样的Request对象调用urlopen

import urllib2
request = urllib2.Request('http://www.example.com', data)
response = urllib2.urlopen(request, timeout=4)
content = response.read()

相关问题 更多 >