2014-02-21 79 views
4

我寫了一個爬蟲從Q &網站獲取信息。由於並非所有字段都始終顯示在頁面中,因此我使用了多個try-excepts來處理這種情況。捕獲異常獲取UnboundLocalError

def answerContentExtractor(loginSession, questionLinkQueue , answerContentList) : 
    while True: 
     URL = questionLinkQueue.get() 
     try: 
      response = loginSession.get(URL,timeout = MAX_WAIT_TIME) 
      raw_data = response.text 

      #These fields must exist, or something went wrong... 
      questionId = re.findall(REGEX,raw_data)[0] 
      answerId = re.findall(REGEX,raw_data)[0] 
      title  = re.findall(REGEX,raw_data)[0] 

     except requests.exceptions.Timeout ,IndexError: 
      print >> sys.stderr, URL + " extraction error..." 
      questionLinkQueue.task_done() 
      continue 

     try: 
      questionInfo = re.findall(REGEX,raw_data)[0] 
     except IndexError: 
      questionInfo = "" 

     try: 
      answerContent = re.findall(REGEX,raw_data)[0] 
     except IndexError: 
      answerContent = "" 

     result = { 
        'questionId' : questionId, 
        'answerId'  : answerId, 
        'title'  : title, 
        'questionInfo' : questionInfo, 
        'answerContent': answerContent 
        } 

     answerContentList.append(result) 
     questionLinkQueue.task_done() 

而這個代碼,有時,可用可不用的,給人運行期間,以下情況例外:

UnboundLocalError: local variable 'IndexError' referenced before assignment 

的行號表示在第二except IndexError:

感謝大家發生錯誤你的建議,願意給予你應得的分數,太差我只能標記一個作爲正確的答案...

+0

錯別字,我用手輸入它條紋一些聯合國需要的行..已編輯.. –

+0

相關:[在一行中有多個例外(塊除外) ](http://stackoverflow.com/questions/6470428/catch-multiple-exceptions-in-one-line-except-block?rq=1) – thefourtheye

回答

6

我認爲這個問題是這一行:

except requests.exceptions.Timeout ,IndexError 

這相當於:

except requests.exceptions.Timeout as IndexError: 

所以,你要指定IndexError到異常被requests.exceptions.Timeout捕獲。錯誤可以通過這個代碼被複制:

try: 
    true 
except NameError, IndexError: 
    print IndexError 
    #name 'true' is not defined 

爲了趕上多個異常使用一個元組:

except (requests.exceptions.Timeout, IndexError): 

而且UnboundLocalError,因爲IndexError是由你的函數中的局部變量處理來了,所以試圖訪問其實際定義之前的值會增加UnboundLocalError錯誤。

>>> 'IndexError' in answerContentExtractor.func_code.co_varnames 
True 

因此,如果這條線不會在運行時(requests.exceptions.Timeout ,IndexError)執行下面然後它使用了可變IndexError將提高UnboundLocalError。示例代碼重現錯誤:

def func(): 
    try: 
     print 
    except NameError, IndexError: 
     pass 
    try: 
     [][1] 
    except IndexError: 
     pass 
func() 
#UnboundLocalError: local variable 'IndexError' referenced before assignment 
+1

它解決了這個問題..謝謝你解釋所有背後的東西場景..除了修復錯誤之外,我對代碼有更好的理解。再次感謝.. –

+0

@PaulLeung很高興幫助。 :) –

2

當你說

except requests.exceptions.Timeout ,IndexError: 

Python會除了requests.exceptions.Timeout錯誤和錯誤對象將是IndexError。這本來應該是這樣的

except (requests.exceptions.Timeout ,IndexError) as e: 
1
except requests.exceptions.Timeout ,IndexError: 

意味着相同except requests.exceptions.Timeout as IndexError

您應該使用

except (requests.exceptions.Timeout, IndexError): 

代替