如何让脚本在迭代中等待,直到重新建立 Internet 连接?

How to make a script wait within an iteration until the Internet connection is reestablished?

我在 for 循环中有一个抓取代码,但需要几个小时才能完成,并且当我的 Internet 连接中断时程序停止。我(认为我)需要的是在爬虫开始时告诉 Python 继续尝试的条件。 我尝试使用 here:

的答案
for w in wordlist:

#some text processing, works fine, returns 'textresult'

    if textresult == '___':  #if there's nothing in the offline resources
        bufferlist = list()
        str1=str()
        mlist=list()  # I use these in scraping

        br = mechanize.Browser()

        tried=0
        while True:
            try:
                br.open("http://the_site_to_scrape/")

                # scraping, with several ifs. Each 'for w' iteration results with scrape_result string.


            except (mechanize.HTTPError, mechanize.URLError) as e:
                tried += 1
                if isinstance(e,mechanize.HTTPError):
                    print e.code
                else:
                    print e.reason.args
            if tried > 4:
                    exit()
                    time.sleep(120)
                    continue
            break

在线时工作。当连接中断时,Python 写入 403 代码并跳过 wordlist 中的那个词,移动到下一个并执行相同的操作。我如何告诉 Python 在迭代中等待连接?

编辑:如果你能至少写一些必要的命令并告诉我它们应该放在我的代码中的什么地方,我将不胜感激,因为我从来没有处理过有异常循环。

编辑 - 解决方案 我应用了 Abhishek Jebaraj 的修改解决方案。我只是添加了一个非常简单的异常处理命令:

except:
    print "connection interrupted"
    time.sleep(30)

此外,Jebaraj 的 getcode 命令会引发错误。在r.getcode之前,我是这样用的:

import urllib

r = urllib.urlopen("http: the site ")

this question 的最佳答案也对我有帮助。

再写一个 while 循环,在其中继续尝试连接到互联网。

它只有在收到状态码 200 时才会中断,然后您可以继续您的程序。

有点喜欢

retry = True
while retry:
    try:
        r = br.open(//your site)
        if r.getcode()/10==20:
            retry = False
    except:
          // code to handle any exception

// rest of your code