Python中For循环中的赋值前引用错误
我从以下地址接收错误的代码:Python中For循环中的赋值前引用错误,python,variables,Python,Variables,我从以下地址接收错误的代码: for img in imgs: if kws.lower() in img['href'].lower(): productLink = f'https://www.{site}.com' + img['href'] price = requests.get(productLink) soup = BeautifulSoup(price.text, 'html.par
for img in imgs:
if kws.lower() in img['href'].lower():
productLink = f'https://www.{site}.com' + img['href']
price = requests.get(productLink)
soup = BeautifulSoup(price.text, 'html.parser')
itemPrice = soup.find(class_='money').text.split('$')[1] + '00'
else:
pass
imageSrc = requests.get(productLink)
错误消息:
imageSrc = requests.get(productLink)
UnboundLocalError: local variable 'productLink' referenced before assignment
对我来说,这没有多大意义,因为我清楚地分配了变量信息。您在if语句中分配了信息,如果img['href']中的kws.lower()为
if,lower():
为false,则productlink
没有值
修理
img中的img的:
如果img['href'].lower()中的kws.lower():
productLink=f'https://www.{site}.com'+img['href']
price=requests.get(productLink)
soup=BeautifulSoup(price.text,'html.parser')
itemPrice=soup.find(class='money').text.split('$')[1]+'00'
imageSrc=requests.get(productLink)
其他:
通过
或者在if语句之前分配imageSrc='