UnboundLocalError:尚未分配本地变量'price'引用

2024-09-30 16:30:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到一个错误:

UnboundLocalError: local variable 'price' referenced before assignment

运行代码时-

from bs4 import BeautifulSoup
import requests

#url = "https://www.amazon.in/FX505DV-Graphics-7-3750H-Windows-FX505DV-AL026T/dp/B07VRLX5Y9/ref=sr_1_1_sspa?keywords=asus+laptop&qid=1569948373&s=gateway&smid=A14CZOWI0VEHLG&sr=8-1-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUFYVTA0NzhaTjQwWU4mZW5jcnlwdGVkSWQ9QTA3OTcwMzMyRlVSWVEwSTVMRloyJmVuY3J5cHRlZEFkSWQ9QTA4ODY2OTcySEdCQTNQOVA5SDgyJndpZGdldE5hbWU9c3BfYXRmJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ=="


def scrape(url):
    """
    Function to scrape price from amazon.com of a given product

    :return: Price

    """
    source = requests.get(url).text


    soup = BeautifulSoup(source, "lxml")

    title = soup.find(id="productTitle").get_text()
    title = title.strip()

    image = soup.find(id="landingImage")
    url_image = image.get("src")

    print("\nProduct Name :", title)
    try:
        price = (
            soup.find(id="priceblock_dealprice").get_text()
            or soup.find(id="priceblock_ourprice").get_text()
        )
        price = price.replace(",", "")
        price = float(price[2:7])
        print("Product Price:", price)
    except AttributeError:
        pass
    try:
        EarlierPrice = soup.find(
            class_="priceBlockStrikePriceString a-text-strike"
        ).get_text()
        EarlierPrice = EarlierPrice.replace(",", "")
        EarlierPrice = float(EarlierPrice[2:])
        #print("Earlier Price:", EarlierPrice)
    except AttributeError:
        pass

    #print("Image:", url_image)

    if price:
        fprice = price
    else:
        fprice =  EarlierPrice

    return fprice

这段代码预计会返回报废产品的价格,但它一直给我这个错误UnboundLocalError


Tags: textimageidurlgettitle错误find
1条回答
网友
1楼 · 发布于 2024-09-30 16:30:46

之所以出现错误UnboundLocalError,是因为引发了子句except AttributeError,而您在其中什么也不做

有两种解决方法:

  1. 在子句try..except..之前定义变量priceEarlierPrice
  2. except子句中指定变量的默认值或引发异常

相关问题 更多 >