简体   繁体   中英

Referenced Before Assignment Error In Python In A For Loop

The Code I Am Receiving The Error From:

    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)

Error Message:

    imageSrc = requests.get(productLink)
UnboundLocalError: local variable 'productLink' referenced before assignment

To Me This Doesn't Make Much Such Because I Clearly Assign The Variable Information.

You Assigned the information in an if statement, if if kws.lower() in img['href'].lower(): is false, then prouductLink has no value.

To fix

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'
            imageSrc = requests.get(productLink)
        else:
            pass

Or assign imageSrc = '' befor the if statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM