2017-04-20 52 views
-1

我對Python非常陌生,這是我第一個真正的項目。我試圖做一個網絡爬蟲,並收到此錯誤UnboundLocalError:分配前引用的局部變量「湯」

import requests 
from bs4 import BeautifulSoup 


def main_spider(max_pages): 
    page = 1 
    while page < max_pages: 
     url = "https://en.wikipedia.org/wiki/Star_Wars" + str(page) 
     source_code = requests.get(url) 
     plain_text = source_code.text 
     soup = BeautifulSoup(plain_text) 
    for link in soup.findAll("a"): 
     href = link.get("href") 
     print(href) 
    page += 1 

main_spider(1) 

以下是錯誤

for link in soup.findAll("a"): 
UnboundLocalError: local variable 'soup' referenced before assignment  
+0

您可以在發佈的代碼上修復縮進嗎?它看起來像'for'循環不在while循環中。在「while」永不成立的情況下,「湯」永遠不會被分配,並且會出現錯誤。但真正的問題是你想在這段時間內加工湯。 – tdelaney

+0

' while page <+ max_pages:'你不需要'+' – tdelaney

+0

現在在上面縮進的代碼。如何在這段時間內處理湯?對不起,如果這是一個愚蠢的問題。 –

回答

0

UnboundLocalError表示有一個代碼路徑,在使用前未分配局部變量。在這種情況下,在分配變量的while循環完成後使用soup。該代碼不考慮while循環從不運行的情況。

這暴露了其他錯誤。首先,for循環應縮進,以使其在while內運行。其次,爲什麼沒有外環運行?這僅僅是條件中的錯字:<+應該是<=

1
import requests 
from bs4 import BeautifulSoup 


def main_spider(max_pages): 
    page = 1 
    while page < max_pages: 
     url = "https://en.wikipedia.org/wiki/Star_Wars" + str(page) 
     source_code = requests.get(url) 
     plain_text = source_code.text 
     soup = BeautifulSoup(plain_text) 
     for link in soup.findAll("a"): 
      href = link.get("href") 
      print(href) 
    page += 1 

main_spider(1) 

在你的情況,soup具有while循環的局部範圍,所以你可以只能在一段時間內訪問它。由於它看起來像是在單頁上做湯(並且使用while循環在頁面之間移動),我相信你希望你的soup.findAll('a')在while循環(每頁基礎上的AKA)內部。

相關問題