python urllib2 检查 Http 错误和 urlerror



这是我的问题:

我的脚本中有 8 个链接,这些链接会根据脚本的其他部分进行更改。在这个链接中,只有 1 个会实际打开我需要的文件,另外 7 个可能会引发 404 错误 (http( 或 10061 错误(连接被拒绝,所以 URLerror(。

我希望我的代码这样做:

如果错误为 404,则不执行任何操作

如果错误为 10061,则不执行任何操作

如果 http.headers 包含 content.type 'PDF',请继续下载。

到目前为止我写的代码:

try:
response = urllib2.urlopen(link) 
except urllib2.HTTPError, e:
if e.code == 404:
print '404'
except urllib2.URLError, e:
if '10061' not in e.args 
#Download code here

嗯,看看你的代码和这 3 行你想要实现的东西,它很可能看起来像这样:(未选中(

try:
response = urllib2.urlopen(link) 
except urllib2.HTTPError, e:
if e.code == 404:
print '404'
except urllib2.URLError, e:
if e.code == 10061:
print '10061'
content_type = response.get_header('content.type', default=None)
if content_type == 'pdf':
#Download code here

最新更新