UnboundLocalError:分配前已引用局部变量“ price”

时间:2019-10-08 10:37:46

标签: python

我遇到了错误:

  

UnboundLocalError:分配前引用了本地变量'price'

在运行代码时-

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

1 个答案:

答案 0 :(得分:2)

发生错误UnboundLocalError是因为引发了except AttributeError子句,您什么也不做。

有两种解决方法:

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