-
Notifications
You must be signed in to change notification settings - Fork 174
fix: replace the CNN exercise with EZ population #2295
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
honzajavorek
wants to merge
3
commits into
master
Choose a base branch
from
honzajavorek/cnn-fix
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
40 changes: 0 additions & 40 deletions
40
.../academy/webscraping/scraping_basics_javascript/exercises/cnn_sports_shortest_article.mjs
This file was deleted.
Oops, something went wrong.
42 changes: 42 additions & 0 deletions
42
sources/academy/webscraping/scraping_basics_javascript/exercises/eurozone_population.mjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import * as cheerio from 'cheerio'; | ||
|
|
||
| async function download(url) { | ||
| const response = await fetch(url); | ||
| if (!response.ok) { | ||
| throw new Error(`HTTP ${response.status}`); | ||
| } | ||
| const html = await response.text(); | ||
| return cheerio.load(html); | ||
| } | ||
|
|
||
| function parsePopulation($) { | ||
| for (const element of $('li').toArray()) { | ||
| const text = $(element).text(); | ||
| if (text.includes('Population')) { | ||
| const digits = text | ||
| .replace('Population:', '') | ||
| .replaceAll(' ', ''); | ||
| return Number.parseInt(digits, 10); | ||
| } | ||
| } | ||
| throw new Error('Population not found'); | ||
| } | ||
|
|
||
| const listingUrl = 'https://european-union.europa.eu/institutions-law-budget/euro/countries-using-euro_en'; | ||
| const $ = await download(listingUrl); | ||
|
|
||
| const $euroCountriesAccordion = $('.ecl-accordion__item').first(); | ||
| const $countryLinks = $euroCountriesAccordion.find('li a'); | ||
|
|
||
| const promises = $countryLinks.toArray().map(async (element) => { | ||
| const countryUrl = new URL($(element).attr('href'), listingUrl).href; | ||
| const $country = await download(countryUrl); | ||
| return parsePopulation($country); | ||
| }); | ||
|
|
||
| const populations = await Promise.all(promises); | ||
| const totalPopulation = populations | ||
| .filter((population) => Number.isInteger(population)) | ||
| .reduce((sum, population) => sum + population, 0); | ||
|
|
||
| console.log(totalPopulation); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
32 changes: 0 additions & 32 deletions
32
sources/academy/webscraping/scraping_basics_python/exercises/cnn_sports_shortest_article.py
This file was deleted.
Oops, something went wrong.
29 changes: 29 additions & 0 deletions
29
sources/academy/webscraping/scraping_basics_python/exercises/eurozone_population.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| import httpx | ||
| from bs4 import BeautifulSoup | ||
| from urllib.parse import urljoin | ||
|
|
||
|
|
||
| def download(url: str) -> BeautifulSoup: | ||
| response = httpx.get(url) | ||
| response.raise_for_status() | ||
| return BeautifulSoup(response.text, "html.parser") | ||
|
|
||
|
|
||
| def parse_population(country_soup: BeautifulSoup) -> int | None: | ||
| for item in country_soup.select("li"): | ||
| if "Population" in item.text: | ||
| digits = item.text.replace("Population:", "").replace(" ", "") | ||
| return int(digits) | ||
| raise ValueError("Population not found") | ||
|
|
||
|
|
||
| listing_url = "https://european-union.europa.eu/institutions-law-budget/euro/countries-using-euro_en" | ||
| listing_soup = download(listing_url) | ||
|
|
||
| total_population = 0 | ||
| euro_countries_accordion = listing_soup.select(".ecl-accordion__item")[0] | ||
| for country_link in euro_countries_accordion.select("li a"): | ||
| country_url = urljoin(listing_url, country_link["href"]) | ||
| country_soup = download(country_url) | ||
| total_population += parse_population(country_soup) | ||
| print(total_population) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Python crashes when
parse_populationreturnsNoneHigh Severity
parse_populationis typedint | Noneand returnsNonewhen nolielement contains "Population". The linetotal_population += parse_population(country_soup)will raise aTypeErrorifNoneis returned, sinceint + Noneis invalid in Python. The JavaScript version correctly handles this by filtering out non-integer values with.filter((population) => Number.isInteger(population))before summing, but the Python version has no equivalent guard.Additional Locations (1)
sources/academy/webscraping/scraping_basics_python/exercises/eurozone_population.py#L11-L16There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The exercise is naive to keep the code simple, so yeah, it relies on the target website a lot and it would crash, but the code is tested, so we'd know. Anyway, I'll add one line to make you happy.