我有一段代码,从给定的url获取一个页面。你知道吗
在try/except子句中,如果发生异常,程序将休眠几秒钟,打印回溯,然后再次递归启动。你知道吗
def fetch_page(self, url):
head = {'User-agent': "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:42.0) Gecko/20100101 Firefox/42.0"}
time.sleep(2)
print "..."
try:
r = requests.get(url, headers=head)
except:
time.sleep(2)
print 'error', url, "Trying again"
traceback.print_exc()
self.fetch_page(url)
r.raise_for_status()
print r.status_code
return r.text
但每当发生异常时,代码都会成功休眠,进行递归调用,打印r.status_code
,然后在r.raise_for_status()
上给出UnboundLocalError
。你知道吗
...
200
Traceback (most recent call last):
File "./calling.py", line 140, in <module>
get_valid_url = Get()
File "./calling.py", line 22, in __init__
self.call()
File "./calling.py", line 44, in call
text = self.fetch_page(link.strip('\n'))
File "./calling.py", line 35, in fetch_page
r.raise_for_status()
UnboundLocalError: local variable 'r' referenced before assignment
现在,如果赋值之前引用了r
,为什么要打印r.status_code
?你知道吗
我的第一个猜测可能是我搞错了递归调用。但这毫无意义。我错过了什么?你知道吗
假设您第一次运行函数并得到404。输入
except
块,然后再次递归调用fetch_page
。假设你这次得了200分。您不需要输入except
块,而是运行到函数的末尾并return r.text
。你知道吗控件然后返回到调用者,这是您之前对
fetch_page
的调用。执行下一行代码,即r.raise_for_status()
。但是在这个调用fetch_page
(顶层调用)时,r
从未真正定义过,因为在try
块中抛出了一个异常。因此,一个UnboundLocalError
。你知道吗一个可能的解决方案-而不是:
将递归调用的结果返回到
fetch_page
:我还建议你做一些更像这样的事情,这样你就不会在不同的缩进水平上得到回报,当你可以避免的时候:
相关问题 更多 >
编程相关推荐