# Solution: Chocolate Scraping with Beautiful Soup (Project)

I was doing this project and just noticed that unlike all projects there is no video walkthrough available for this one. So thought it might help someone who is having trouble completing it.

from bs4 import BeautifulSoup
import requests
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

soup = BeautifulSoup(webpage.content, âhtml.parserâ)

ratings_data = soup.find_all(attrs={âclassâ: âRatingâ})
ratings =
for rating in ratings_data[1:]:
ratings.append(float(rating.string))
print(ratings)

plt.hist(ratings)
plt.show()

company_data = soup.select(â.Companyâ)
companies =
for company in company_data[1:]:
companies.append(company.string)
print(companies)

dict = {
âCompanyâ: companies,
âRatingâ: ratings
}
df = pd.DataFrame.from_dict(dict)

avg_ratings = df.groupby(âCompanyâ).Rating.mean()
top_ten = avg_ratings.nlargest(10)
print(top_ten)

cocoa_data = soup.select(â.CocoaPercentâ)
cocoa_pcts =
for cocoa_pct in cocoa_data[1:]:
cocoa_pcts.append(int(float(cocoa_pct.string[:-1])))
print(cocoa_pcts)

df[âCocoaPercentageâ] = cocoa_pcts

plt.cla()
plt.scatter(df.CocoaPercentage, df.Rating)
z = np.polyfit(df.CocoaPercentage, df.Rating, 1)
line_function = np.poly1d(z)
plt.plot(df.CocoaPercentage, line_function(df.CocoaPercentage), ârââ)
plt.show()

18 Likes

Definitely love that! Thanks!

3 Likes

Thank you - much appreciated. This wasnât the best-written of modules.

5 Likes

Add my thanks! When you do that, it helps give us a reference point to check our own efforts and promotes better learning.

1 Like

Does this run super slow for anyone else? It like breaks my browser at the histogram part. I really wish this module had a video solution : (

I had to go through the same issue, it was super slowâŚ
I donât know maybe itâs something to do with the backend or the database where the data is being fetched from.

hey all,
If you guys run this module on jupyter notebook, itâs quick and you donât need to go around to look at your graphs!

Life saving is what this is

It doesnât run. LOL
Returns an error for the line:
ratings_data = soup.find_all(attrs={âclassâ: âRatingâ})

2 Likes

Excellent job. Did you do it on the jupyter notebook? It seems you did not " import codecademylib3_seaborn".

I have trouble to do the project on jupyter. Do I need to import more âmodulesâ ?

hi, do you import extra stuff to get it working on jupyter? Thank you.

Hereâs my âas few lines of code as possibleâ solution:

``````import codecademylib3_seaborn
from bs4 import BeautifulSoup
import requests
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# 1. Access data

soup = BeautifulSoup(web.content, 'html.parser')

# 2. Grab relevant data

ratings = [float(rating.get_text()) for rating in soup.find_all(attrs={"class": 'Rating'})[1:]]
companies = [company.get_text() for company in soup.find_all(attrs={"class": "Company"})[1:]]
cocoa = [float(cocoa.get_text()[:-1]) for cocoa in soup.find_all(attrs={"class": "CocoaPercent"})[1:]]

# 3. Create df

df = pd.DataFrame.from_dict({"Company": companies, "Rating": ratings, "CocoaPercentage": cocoa})

# 4. Ratings Histogram

plt.hist(ratings)
plt.show()
plt.clf()

#3. Top 10 chocolate by Rating

mean_ratings = df.groupby("Company").Rating.mean()
top_ten = mean_ratings.nlargest(10)

# 4. Cocoa / Rating relationship

plt.scatter(df.CocoaPercentage, df.Rating)
z = np.polyfit(df.CocoaPercentage, df.Rating, 1)
line_function = np.poly1d(z)
plt.plot(df.CocoaPercentage, line_function(df.CocoaPercentage), "r--")

plt.show()
``````
3 Likes

This was super helpful, thank you. I spent 30 minutes trying to work out why my scatter graph didnât look right until I noticed that it had the same y-axis as the histogram. Turns out thatâs what plt.clf() is for!

Thank you so much. This was extremly difficult