![](/img/trans.png)
[英]UnboundLocalError: local variable 'userOrder' referenced before assignment, however it had no error being called in a similar manner earlier
[英]Variable had been assigned before referencing, but still getting an UnboundLocalError
我想知道為什么當我的scrape_quotes()
function 運行時它會拋出一個錯誤,說UnboundLocalError: local variable 'url' referenced before assignment
(第 11 行)。 當我在引用它之前分配它時,為什么它會這樣做?
無論哪種方式,為什么這是一個錯誤,當我訪問BASE_URL
時沒有錯誤? 我非常困惑...
import requests
from bs4 import BeautifulSoup
from time import sleep
from random import choice
BASE_URL = "http://quotes.toscrape.com"
url = "/page/1/"
def scrape_quotes():
all_quotes = []
while url:
response = requests.get(f"{BASE_URL}{url}")
print(f"Now Scraping {BASE_URL}{url}")
soup = BeautifulSoup(response.text, "html.parser")
quotes = soup.select(".quote")
for quote in quotes:
all_quotes.append({
"quote" : quote.select(".text")[0].get_text(),
"author" : quote.select(".author")[0].get_text(),
"bio-link" : quote.select("a")[0].attrs['href']
})
next_btn = soup.select(".next")
url = next_btn[0].select("a")[0].attrs['href'] if next_btn else None
sleep(2)
return all_quotes
因為它被定義為全局變量。 要修改它,您需要使用global
關鍵字,即
global url
# scrape
url = next_url
但是,我建議將其分配在 function 內。 如果您也在 function 之外使用它,則將其作為參數傳遞給 function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.