[英]How can I handle “UnboundLocalError” in Python3.6?
I have code like below which is in the part a Class: 我有下面的代码,其中一部分是类:
def getHtmlResponse(self, inUrl):
while True:
try:
res = urllib.request.urlopen(inUrl)
html = res.read()
soup = BeautifulSoup(html, 'html.parser')
except urllib.error.URLError:
pass
break
return soup
Sometimes, I have an error message like below: 有时,我会收到如下错误消息:
File "/Users/chongwonshin/PycharmProjects/Crawler_test/Content_crawler.py", line 99, in getHtmlResponse
return soup
UnboundLocalError: local variable 'soup' referenced before assignment
This error happens only few times in a number of runs. 在多次运行中,此错误仅发生几次。 How can I handle this type of error? 如何处理此类错误?
soup will not get initiliazed if an exception is raised in the first 2 lines of the try block. 如果try块的前两行出现异常,汤将不会初始化。 So you can initiliaze soup
once more in except block. 因此,除了块状,您可以再次初始化soup
。
def getHtmlResponse(self, inUrl):
while True:
try:
res = urllib.request.urlopen(inUrl)
html = res.read()
soup = BeautifulSoup(html, 'html.parser')
except urllib.error.URLError:
soup = ''
pass
break
return soup
Let's simplify your code. 让我们简化您的代码。 Since you always break
out of the loop, the loop is effectively a no-op and can be removed: 由于您总是会break
循环,因此循环实际上是无操作的,可以将其删除:
def getHtmlResponse(self, inUrl):
try:
res = urllib.request.urlopen(inUrl)
html = res.read()
soup = BeautifulSoup(html, 'html.parser')
except urllib.error.URLError:
pass
return soup
Now consider what happens if the BeautifulSoup()
call throws an exception: the assignment to soup
never happens yet your code still tries to return it. 现在考虑如果BeautifulSoup()
调用引发异常会发生什么:对soup
的赋值永远不会发生,但您的代码仍会尝试返回它。
You need to decide what you want to do if this happens. 如果发生这种情况,您需要决定要做什么。 Returning an object that doesn't exist is clearly not an option. 返回一个不存在的对象显然不是一种选择。 You could, for example, choose to return None
and modify your code accordingly. 例如,您可以选择返回None
并相应地修改代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.