urllib2 超时 [英] urllib2 timeout

查看:36
本文介绍了urllib2 超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的代码使用 urllib2 库,我使用了很多 (urlopen) loadurl

i'm using urllib2 library for my code, i'm using a lot of (urlopen) loadurl

我的网络出现问题,当我浏览网站时,有时我的浏览器卡在连接"到某个网站上,有时我的浏览器返回超时

i have a problem on my network, when i'm browsing sites, sometimes my browser gets stuck on "Connecting" to a certain website and sometimes my browser returns a timeout

我的问题是,如果我在我的代码上使用 urllib2,它会在尝试连接到某个网站的时间过长时超时,否则代码会卡在该行上.

My question is if i use urllib2 on my code it can timeout when trying to connect for too long to a certain website or the code will get stuck on that line.

我知道 urllib2 可以处理超时而无需在代码中指定它,但它可以应用于这种情况?

i know that urllib2 can handle timeouts without specifying it on code but it can apply for this kind of situation ?

感谢您的时间

def checker(self)
 try:
   html = self.loadurl("MY URL HERE")
   if self.ip_ != html:
(...)
 except Exeption, error:
   html = "bad"

推荐答案

根据我的小调查,urllib2.urlopen() 函数是在 python 2.6 中添加的

from my small research, the urllib2.urlopen() function is added in python 2.6

所以,超时问题应该通过向urllib2.urlopen函数发送自定义超时来解决.代码应该是这样的;

so, the timeout problem should be resolved by sending custom timeout to the urllib2.urlopen function. the code should look like this ;

response = urllib2.urlopen("---在此处插入网址---", None, your-timeout-value)

your-timeout-value 参数是一个可选参数,它以秒为单位定义超时.

the your-timeout-value parameter is an optional parameter which defines the timeout in seconds.

根据您的评论,我知道您不需要等待太长时间的代码,那么您应该拥有以下代码以免卡住;

EDIT : According to your comment, I got that you don't need the code for waiting too long then you should have the following code to not get stuck;

import socket
import urllib2

socket.setdefaulttimeout(10)

10 可以根据与连接速度相关的数学公式进行更改网站加载时间.

10 can be changed according to a math formula related to the connection speed & website loading time.

这篇关于urllib2 超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆