Advertisement
GeorgiLukanov87

task-3

Jan 22nd, 2024
929
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. import requests
  2. from bs4 import BeautifulSoup
  3.  
  4. # Step a: Open the webpage
  5. url = 'https://en.wikipedia.org/wiki/List_of_European_Union_member_states_by_population'
  6. response = requests.get(url)
  7. soup = BeautifulSoup(response.text, 'html.parser')
  8.  
  9. # Step b: Extract data from the table
  10. table = soup.find('table', {'class': 'wikitable'})
  11. countries_data = []
  12.  
  13. for row in table.find_all('tr')[2:]:
  14.     columns = row.find_all('td')
  15.     country = columns[1].text.strip()
  16.     population = int(columns[2].text.replace(',', '').strip())
  17.     countries_data.append({country: {'country_population': population}})
  18.  
  19. # Step c: Create the countries_dictionary
  20. countries_dictionary = {}
  21.  
  22. for data in countries_data:
  23.     countries_dictionary.update(data)
  24.  
  25. # Step d: Calculate total_country_population and country_population_percentage
  26. total_country_population = sum(data['country_population'] for data in countries_dictionary.values())
  27.  
  28. for country, data in countries_dictionary.items():
  29.     country_percentage = (data['country_population'] / total_country_population) * 100
  30.     data['country_population_percentage'] = round(country_percentage, 1)
  31.  
  32.  
  33.  
  34. for country,cdata in countries_dictionary.items():
  35.     print(country)
  36.     print(cdata)
  37.  
  38.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement