我对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
您可以在发布的代码上修复缩进吗?它看起来像'for'循环不在while循环中。在“while”永不成立的情况下,“汤”永远不会被分配,并且会出现错误。但真正的问题是你想在这段时间内加工汤。 – tdelaney
' while page <+ max_pages:'你不需要'+' – tdelaney
现在在上面缩进的代码。如何在这段时间内处理汤?对不起,如果这是一个愚蠢的问题。 –