def rank_us(asin,site):
...
url = "https://www.amazon.com/dp/" + asin
try:
req=requests.get(url,headers=headers)
req.encoding='utf-8'
html=req.text
except requests.exceptions.ConnectionError:
print("retry line the internet...")
rank_us(asin,site)
html_x = etree.HTML(html)
以上代碼,幾時條件符合,執行到了except 中的 rank_us函式里面
然后報錯,
UnboundLocalError: local variable 'html' referenced before assignment
最近遇到好多這個問題,嵌套函式執行了,卻沒有結束當前的執行....
求解
uj5u.com熱心網友回復:
你想做什么?你的 try except 只是捕獲 網路連接例外 。 其他例外不捕獲。
看代碼, 應該是 出現例外了, html 沒有賦值,
到 html_x = etree.HTML(html) 這里就出錯了。
uj5u.com熱心網友回復:
這樣能捕獲UnboundLocalError 的例外。
def rank_us(asin,site):
...
url = "https://www.amazon.com/dp/" + asin
try:
req=requests.get(url,headers=headers)
req.encoding='utf-8'
html=req.text
except requests.exceptions.ConnectionError:
print("retry line the internet...")
rank_us(asin,site)
try:
html_x = etree.HTML(html)
except Exception as e:
print("出錯啦 ")
print(repr(e))
uj5u.com熱心網友回復:
我這里的本意呢,就是說處理網路連接例外重連的,然后就用嵌套函式重新連接
我這里也print("retry line the internet")了,也就是進入了我的嵌套函式里面,就不會進行下面的
html_x = etree.HTML(html) #這里報錯的原因的是因為上面的獲取html例外了嘛,沒有得到html,也就是html未定義就進行呼叫所以報錯
但是問題來了, 網路連接例外,就進入嵌套重新連接了吧?為何還會執行
html_x = etree.HTML(html) #
再引起錯誤呢
uj5u.com熱心網友回復:
UnboundLocalError: local variable 'html' referenced before assignment
這個錯誤的是我們的變數還沒定義就進行呼叫了
uj5u.com熱心網友回復:
try except 就是個塊,html_x = etree.HTML(html)
在 try except 塊 外, try except 的情況 不影響 html_x = etree.HTML(html) 的執行。
你可以把 html_x = etree.HTML(html) 放到塊里, 或者加 標識 ,判斷后再執行 html_x = etree.HTML(html)
def rank_us(asin,site):
...
url = "https://www.amazon.com/dp/" + asin
ret_flag = False
try:
req=requests.get(url,headers=headers)
req.encoding='utf-8'
html=req.text
ret_flag = True
except requests.exceptions.ConnectionError:
print("retry line the internet...")
rank_us(asin,site)
if ret_flag:
html_x = etree.HTML(html)
uj5u.com熱心網友回復:
改成這樣穩妥些, 把所有例外都捕獲。
def rank_us(asin,site):
...
url = "https://www.amazon.com/dp/" + asin
ret_flag = False
try:
req=requests.get(url,headers=headers)
req.encoding='utf-8'
html=req.text
ret_flag = True
except Exception as e :
print("出錯啦 ")
print(repr(e))
rank_us(asin,site)
if ret_flag:
html_x = etree.HTML(html)
uj5u.com熱心網友回復:
有點跑題啦,不過還是謝謝老哥
主要是嵌套函式的,為何還繼續進行下去的,不知道價格return 會不會好點
還有except Exception as e:
這個,其實有很多例外是無法捕捉的,例如的話selenium模塊里面就已經有很多無法捕捉的異常
需要自定 except selenium.**自定義捕捉他報錯的型別才能捕捉到
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/122796.html
