簡體   English   中英

python urllib2檢查Http錯誤和urlerror

[英]python urllib2 check for both Http error AND 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

嗯,看一下您的代碼,這三行您想要實現的代碼很可能看起來像這樣:(未選中)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM