Convert string to a float (Chocolate Soup Web Scraping Q7)

I’ve tried numerous ways to convert the string ‘rating’ to a float (lines 21-25). Any suggestions? Here’s my latest code:

import codecademylib3_seaborn from bs4 import BeautifulSoup import requests import pandas as pd import matplotlib.pyplot as plt import numpy as np webpage = requests.get("https://content.codecademy.com/courses/beautifulsoup/cacao/index.html") soup = BeautifulSoup(webpage.content, "html.parser") soup.find_all(attrs={"class", "Rating"}) ratings = [] for rating in soup.select(".Rating")[1:]: ratings.append(rating.get_text()) float(rating) companies = [] for name in soup.select(".Company")[1:]: companies.append(name.get_text())

Your code seems to have lost its indentation which makes it a little harder to read. What’s the type of rating? Typically a simply call to float would do it, e.g. float('3.5') or float(-5) but it depends on the type. You may need some steps before this call if it’s not something that float understands- https://docs.python.org/3/library/functions.html#float

The type of ‘rating’ is Tag. Perhaps that’s where I’m going wrong? Reposted code with better readability.

import codecademylib3_seaborn from bs4 import BeautifulSoup import requests import pandas as pd import matplotlib.pyplot as plt import numpy as np webpage = requests.get("https://content.codecademy.com/courses/beautifulsoup/cacao/index.html") soup = BeautifulSoup(webpage.content, "html.parser") soup.find_all(attrs={"class", "Rating"}) ratings = [] for rating in soup.select(".Rating")[1:]: ratings.append(rating.get_text()) print(type(rating)) companies = [] for name in soup.select(".Company")[1:]: companies.append(name.get_text()) d = {"Company": companies, "Rating": ratings} df = pd.DataFrame.from_dict(d)
1 Like

That makes sense, there must be a way to extract the relevant information from that object or perhaps the instructions meant for you to do something a little different beforehand. I’m afraid it’s not a project I’m familiar with.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.