简体   繁体   English

urllib2超时

[英]urllib2 timeout

i'm using urllib2 library for my code, i'm using a lot of (urlopen) EDIT: loadurl 我正在为我的代码使用urllib2库,我正在使用很多(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 我的网络存在问题,当我浏览网站时,有时我的浏览器卡在“连接”到某个网站上,有时我的浏览器返回超时

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 ? 我知道urllib2可以处理超时,而无需在代码上指定超时,但是它可以适用于这种情况?

Thanks for your time 谢谢你的时间

EDIT : 编辑:

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

from my small research, the urllib2.urlopen() function is added in python 2.6 根据我的小型研究,在python 2.6中添加了urllib2.urlopen()函数

so, the timeout problem should be resolved by sending custom timeout to the urllib2.urlopen function. 因此,应通过将自定义超时发送到urllib2.urlopen函数来解决超时问题。 the code should look like this ; 代码应该像这样;

response = urllib2.urlopen( "---insert url here---", None, your-timeout-value)

the your-timeout-value parameter is an optional parameter which defines the timeout in seconds. your-timeout-value参数是可选参数,用于定义超时(以秒为单位)。

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 can be changed according to a math formula related to the connection speed & website loading time. 可以根据与连接速度和网站加载时间有关的数学公式来更改10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM