python网络爬虫 - 设定重试次数内反复抓取

Posted Master HaKu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python网络爬虫 - 设定重试次数内反复抓取相关的知识,希望对你有一定的参考价值。

import urllib.request

def download(url, num_retries=2):
    print(Downloading:, url)
    try:
        html = urllib.request.urlopen(url).read()
    except urllib.URLError as e:
        print(Download error: % e.reason)
        html = None
        if num_retries > 0:
            if hasattr(e, code) and 500 <= e.code < 600:
                # recursively retry 5xx HTTP errors
                return download(url, num_retries-1)
    return html
    
url = http://www.google.com
print(download(url, 3))

 

以上是关于python网络爬虫 - 设定重试次数内反复抓取的主要内容,如果未能解决你的问题,请参考以下文章