2017-04-20 90 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)内部。

相关问题