关于下载网页重试的问题

zkw261123 2018-03-08 02:04:58
这是我的代码,实现下载网页,失败重试2次的功能:

def downloadurl_with_retries(url,retries=2):
print('Downloading: %s'%url)
try:
with urllib.request.urlopen(url) as html:
return html.read()
except urllib.UrlError as e:
print('Download Error: %s'%e.reason)
if(retries>0):
if(hasattr(e,'code') and 500<=e.code<600):
##hasattr(object,name),判断对象object是否有名为name的属性或方法
print('Retry %d:'%retries)
return downloadurl(url,retries-1)
else:
return None

然后执行:

print(downloadurl_with_retries('http://httpstat.us/500'))

这个网址会返回一个500 Server Error
我期待的结果是执行时会失败并重试2次,但是执行时失败就直接结束了,如图:


为什么不重试2次?
...全文
242 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
zkw261123 2018-03-08
  • 打赏
  • 举报
回复
引用 2 楼 u012536120 的回复:
为什么没执行两次,因为代码都没执行完。就报错了 看你的报错信息,它说这句有问题——print('Download Error: %s'%e.reason)
我把这句注释了,出现了新的错误HTTPError 我把
except urllib.UrlError as e:
改成:
except urllib.error.HTTPError as e:
得到了我期望的结果 谢谢
sanGuo_uu 2018-03-08
  • 打赏
  • 举报
回复
为什么没执行两次,因为代码都没执行完。就报错了 看你的报错信息,它说这句有问题——print('Download Error: %s'%e.reason)
sanGuo_uu 2018-03-08
  • 打赏
  • 举报
回复
??
#!/usr/bin/python
# -*- coding: utf-8 -*-

from urllib import request
url='http://httpstat.us/500'

def downloadurl_with_retries(url,retries=2):
    print('Downloading: %s'%url)
    try:
        with request.urlopen(url) as html:
            return html.read()
    except Exception as e:
        print('Download Error: %s'%e)
        if(retries>0):
            if(hasattr(e,'code') and 500<=e.code<600):
                ##hasattr(object,name),判断对象object是否有名为name的属性或方法
                print('Retry %d:'%retries)
                return downloadurl_with_retries(url,retries-1)
        else:
            return None

html=downloadurl_with_retries(url,2)
print(html)

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧