Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

python - Invalid Operation with Decimal

I'm using beautiful soup to extract information from a website and to get the price of an item. I used the code below to create a variable names prices to store the information. Then I created a loop to iterate through all of the items and now I'm trying to compare it to another variable named price_thres to determine if its less than or equal to the amount. Running this code prints a few of the correct values but it also prints

    price_in_dec = Decimal(i.text)
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]
prices = soup.find_all("span", itemprop="price")

for i in prices:
    price_in_dec = Decimal(i.text)
    if price_in_dec <= price_thres:
        print(price_in_dec)
question from:https://stackoverflow.com/questions/65878027/invalid-operation-with-decimal

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You seem to have commas (,) in some of your prices.

Try this:

import locale

# Set to US locale
locale.setlocale(locale.LC_ALL, 'USA')

prices = soup.find_all("span", itemprop="price")

for i in prices:
    price_in_dec = Decimal(locale.atof(i.text))
    if price_in_dec <= price_thres:
        print(price_in_dec)

By using the correct locale, you can parse the prices according to the way you write them in the US.

Another option would be to simply remove commas using i.text.replace(",", "").


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...