没有连接到网站时如何暂停程序?


没有

互联网连接时如何暂停程序?该程序正在从网站(urllib2,beautifulsoup(获取信息,但是如果用户失去了与网站的连接,我该如何暂停程序,直到用户输入单词"START"?

检查 html 并在为空或检测到某些内容(如错误代码(时暂停。然后做出反应。

对请求也使用超时:对于 curl Im,对整个请求使用连接超时和最大时间超时。

要解决用户输入问题,请执行以下操作:

s = raw_input("Continue?")
if s == "START":
    #re run your code
当您使用

urllib2 请求时,它将使用默认超时,通常为 3600 秒,因为您可以将超时更改为其他超时

urllib2.urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]](

所以你可以写一些类似的东西

urllib2.urlopen("www.example.com", timeout=60) # to set a timeout for 60 seconds

你可以用 try 包装它,除了

while True: #this can be a loop of all the url you get
 try:
   request = urllib2.urlopen("www.example.com", timeout=60)
   # manipulate the request object 
 except urllib2.URLError, e:
  s = raw_input("timeout detected continue [y/n]")
  if s == "Y":
    continue
  else:
    break
 time.sleep(1)

最新更新