【发布时间】:2015-05-18 09:46:10
【问题描述】:
我有一个程序可以从网站下载页面,在其中找到图片链接并下载这些图片。如果我尝试在具有快速和稳定 Internet 连接的计算机上运行该程序 - 几天和几周内一切正常。但是,如果我在 Internet 连接缓慢或不稳定的计算机上尝试这个程序——我有一个问题——“try-except”模块似乎无法正常工作。
---此功能下载内容-任何内容(页面或图片)
def downl(self,addr,cook,head2,errmess):
global result
try:
result=requests.get(addr, cookies=cook, headers=head2)
except:
print(errmess) # error message
time.sleep(5)
return result
我将页面链接发送到该函数,然后其他函数在该页面中查找picture_link,然后我发送到相同的函数(downl)picture_link。在此之后,我将函数 (downl) 的结果保存为 .jpg 文件。正如我所说 - 在具有正常互联网连接的计算机上一切正常。结果,我的硬盘上有 5、10 或 5000 张图片。
但让我举一个小例子来说明互联网连接不好会发生什么。假设我们有 2 页,每页 1 张图片。
step 1) downloading 1st page (def downl)
step 2) taking picture_link from it
step 3) downloading picture (def downl)
step 4) saving 1st picture to hdd 1.jpg
step 5) downloading 2nd page (def downl)
step 6) taking picture_link from it
step 7) downloading picture (def downl) and receivind error message (errmess)
step 8) saving 2nd picture to hdd 2.jpg
例如:第一张图片可能是具有适当内容的普通 jpg。第二张图片将是带有 jpg 扩展名的文件,但将有第二页作为其内容(它将是通常的 html 文件,以错误的扩展名“jpg”保存)
换句话说:在第二张图片的下载过程中互联网出现问题,程序打印了一个关于它的错误(errmess),但是在无数次重试(正如我的函数中所假设的那样)它以某种方式通过了 try-except 块并返回之前的结果(第 2 页),保存为第 2 张图片。
请帮忙!如何让这个 try-except(或请求)永远工作,直到它下载它应该下载的内容(无论互联网连接发生什么错误),而不是通过以前的结果。
非常感谢您的时间和关注。
【问题讨论】:
-
global result导致“失败”结果返回最后一个成功结果。result没有重新定义,仍然是return-ed。抛出的确切错误是什么?ConnectionError? -
是的。我知道由于全局“结果”,我得到了以前的结果。但问题是关于其他事情 - 为什么程序会通过 try-except,它应该永远在其中循环,直到它下载图片。关于确切的错误 - 我今晚会在网络不好的电脑前查看确切的错误。
标签: python-3.x python-requests try-except