I'm trying to save price data to an Excel file. I got the data from a website as text, and now I want to create an array with the data in it. My code thus far looks like this:
r = requests.get(url)
data = BeautifulSoup(r.text)
my_prices = []
prices = data.find_all("example", {"class":"example"})
index = 0
for price in prices:
print prices[index].text
index += 1
My output looks like this:
€2,75
€9,00
€17,50
€2,75
€3,00
€2,50
€2,75
€4,00
€4,00
€0,50
€2,50
€2,50
€3,25
€2,50
€2,50
€2,50
€2,50
€2,50
€4,50
€2,50
€2,00
€4,00
€10,50
€16,50
If tried to ad an array in the for loop, but I can't figure out how. I'm a beginner in Python! Thanks in advance.
You can use a list comprehension to iterate over the "example" prices and extract the text for each price:
r = requests.get(url)
data = BeautifulSoup(r.text)
my_prices = [price.text for price in data.find_all("example", {"class":"example"})]
Now your question is how to change the text to digits. If you want to retain them as strings then you can strip off the currency symbol and optionally the comma could be replaced with a decimal point if that makes sense in your locale. This method uses unicode.translate() in Python 2:
trans_table = {ord(u'\u20ac'): None, ord(u','): u'.'}
my_prices = [price.text.translate(trans_table)
for price in data.find_all("example", {"class":"example"})]
If you want them as floats:
my_prices = [float(price.text.translate(trans_table))
for price in data.find_all("example", {"class":"example"})]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With