我编写了一个爬虫来从问答网站中获取信息。由于并非所有字段都始终显示在页面中,因此我使用了多个 try-excepts 来处理这种情况。
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:
谢谢大家的建议,很想给你应得的分数,可惜我只能打一个正确答案......
最佳答案
我认为问题出在这一行:
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
关于python - 捕获异常得到 UnboundLocalError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21927065/