diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 79711189ab..8359b02df9 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -248,6 +248,11 @@ jobs: assert_header "http://localhost:8080/platform/actors/running/standby.md" "Location" "^Location: http://[^/]*/actors/running/server-actors[.]md$" assert_header "http://localhost:8080/actors/development/programming-interface/standby" "Location" "^Location: http://[^/]*/actors/development/programming-interface/server-actors$" + echo "๐Ÿงช Checking removed legacy JS course redirects..." + assert_header "http://localhost:8080/academy/scraping-basics-javascript/legacy" "Location" "^Location: http://[^/]*/academy/scraping-basics-javascript$" + assert_header "http://localhost:8080/academy/scraping-basics-javascript/legacy/data-extraction/save-to-csv.md" "Location" "^Location: http://[^/]*/academy/scraping-basics-javascript/saving-data[.]md$" + assert_header "http://localhost:8080/academy/web-scraping-for-beginners/challenge" "Location" "^Location: http://[^/]*/academy/expert-scraping-with-apify$" + echo "โœ… All Nginx header checks passed." - name: Verify per-page .md navigation headers diff --git a/nginx.conf b/nginx.conf index d3b1762915..6e00feffa1 100644 --- a/nginx.conf +++ b/nginx.conf @@ -338,7 +338,7 @@ server { rewrite ^/schedules$ /platform/schedules permanent; rewrite ^/scraping$ /platform/actors/running permanent; rewrite ^/tutorials$ /platform/actors/running permanent; - rewrite ^/web-scraping-101$ /academy/scraping-basics-javascript?legacy-js-course=/ permanent; + rewrite ^/web-scraping-101$ /academy/scraping-basics-javascript permanent; rewrite ^/access-rights/list-of-permissions$ /platform/collaboration/list-of-permissions permanent; rewrite ^/access-rights/organization-account$ /platform/collaboration/organization-account permanent; rewrite ^/actor/development$ /platform/actors/development permanent; @@ -459,18 +459,18 @@ server { rewrite ^/academy/apify-platform/getting-started/apify-client$ /academy/getting-started/apify-client permanent; rewrite ^/academy/apify-platform/getting-started/creating-actors$ /academy/getting-started/creating-actors permanent; rewrite ^/academy/apify-platform/getting-started/inputs-outputs$ /academy/getting-started/inputs-outputs permanent; - rewrite ^/academy/web-scraping-for-beginners/data-collection$ /academy/scraping-basics-javascript/devtools-inspecting?legacy-js-course=/data-collection permanent; + rewrite ^/academy/web-scraping-for-beginners/data-collection$ /academy/scraping-basics-javascript/devtools-inspecting permanent; rewrite ^/academy/puppeteer-playwright/executing-scripts/extracting-data$ /academy/puppeteer-playwright/executing-scripts/collecting-data permanent; - rewrite ^/academy/web-scraping-for-beginners/data-collection/browser-devtools$ /academy/scraping-basics-javascript/devtools-inspecting?legacy-js-course=/data-collection/browser-devtools permanent; - rewrite ^/academy/web-scraping-for-beginners/data-collection/computer-preparation$ /academy/scraping-basics-javascript/downloading-html?legacy-js-course=/data-collection/computer-preparation permanent; - rewrite ^/academy/web-scraping-for-beginners/data-collection/devtools-continued$ /academy/scraping-basics-javascript/devtools-extracting-data?legacy-js-course=/data-collection/devtools-continued permanent; - rewrite ^/academy/web-scraping-for-beginners/data-collection/node-continued$ /academy/scraping-basics-javascript/extracting-data?legacy-js-course=/data-collection/node-continued permanent; - rewrite ^/academy/web-scraping-for-beginners/data-collection/node-js-scraper$ /academy/scraping-basics-javascript/downloading-html?legacy-js-course=/data-collection/node-js-scraper permanent; - rewrite ^/academy/web-scraping-for-beginners/data-collection/project-setup$ /academy/scraping-basics-javascript/downloading-html?legacy-js-course=/data-collection/project-setup permanent; - rewrite ^/academy/web-scraping-for-beginners/data-collection/save-to-csv$ /academy/scraping-basics-javascript/saving-data?legacy-js-course=/data-collection/save-to-csv permanent; - rewrite ^/academy/web-scraping-for-beginners/data-collection/using-devtools$ /academy/scraping-basics-javascript/devtools-locating-elements?legacy-js-course=/data-collection/using-devtools permanent; - rewrite ^/academy/web-scraping-for-beginners/crawling/processing-data$ /academy/scraping-basics-javascript/framework?legacy-js-course=/crawling/processing-data permanent; - rewrite ^/academy/web-scraping-for-beginners/crawling/recap-collection-basics$ /academy/scraping-basics-javascript/extracting-data?legacy-js-course=/crawling/recap-collection-basics permanent; + rewrite ^/academy/web-scraping-for-beginners/data-collection/browser-devtools$ /academy/scraping-basics-javascript/devtools-inspecting permanent; + rewrite ^/academy/web-scraping-for-beginners/data-collection/computer-preparation$ /academy/scraping-basics-javascript/downloading-html permanent; + rewrite ^/academy/web-scraping-for-beginners/data-collection/devtools-continued$ /academy/scraping-basics-javascript/devtools-extracting-data permanent; + rewrite ^/academy/web-scraping-for-beginners/data-collection/node-continued$ /academy/scraping-basics-javascript/extracting-data permanent; + rewrite ^/academy/web-scraping-for-beginners/data-collection/node-js-scraper$ /academy/scraping-basics-javascript/downloading-html permanent; + rewrite ^/academy/web-scraping-for-beginners/data-collection/project-setup$ /academy/scraping-basics-javascript/downloading-html permanent; + rewrite ^/academy/web-scraping-for-beginners/data-collection/save-to-csv$ /academy/scraping-basics-javascript/saving-data permanent; + rewrite ^/academy/web-scraping-for-beginners/data-collection/using-devtools$ /academy/scraping-basics-javascript/devtools-locating-elements permanent; + rewrite ^/academy/web-scraping-for-beginners/crawling/processing-data$ /academy/scraping-basics-javascript/framework permanent; + rewrite ^/academy/web-scraping-for-beginners/crawling/recap-collection-basics$ /academy/scraping-basics-javascript/extracting-data permanent; rewrite ^/academy/php/using-apify-scraper-with-php$ /academy/php/use-apify-from-php permanent; rewrite ^/api/client/?$ /api redirect; @@ -577,7 +577,7 @@ server { # Articles moved from the platform documentation to the Academy # Web Scraping 101 - rewrite ^/platform/web-scraping-101$ /academy/scraping-basics-javascript?legacy-js-course=/ redirect; + rewrite ^/platform/web-scraping-101$ /academy/scraping-basics-javascript redirect; rewrite ^/platform/web-scraping-101/anti-scraping-techniques$ /academy/anti-scraping/techniques redirect; rewrite ^/platform/web-scraping-101/web-scraping-techniques$ / redirect; # RPA @@ -647,32 +647,60 @@ server { rewrite ^/academy/php$ /academy/php/use-apify-from-php redirect; # not permanent in case we want to reuse /php in the future # Academy: replacing the 'Web Scraping for Beginners' course - rewrite ^/academy/web-scraping-for-beginners/best-practices$ /academy/scraping-basics-javascript?legacy-js-course=/best-practices permanent; - rewrite ^/academy/web-scraping-for-beginners/introduction$ /academy/scraping-basics-javascript?legacy-js-course=/introduction permanent; - rewrite ^/academy/web-scraping-for-beginners/challenge/initializing-and-setting-up$ /academy/scraping-basics-javascript?legacy-js-course=/challenge/initializing-and-setting-up permanent; - rewrite ^/academy/web-scraping-for-beginners/challenge/modularity$ /academy/scraping-basics-javascript?legacy-js-course=/challenge/modularity permanent; - rewrite ^/academy/web-scraping-for-beginners/challenge/scraping-amazon$ /academy/scraping-basics-javascript?legacy-js-course=/challenge/scraping-amazon permanent; - rewrite ^/academy/web-scraping-for-beginners/challenge$ /academy/scraping-basics-javascript?legacy-js-course=/challenge permanent; - rewrite ^/academy/web-scraping-for-beginners/crawling/exporting-data$ /academy/scraping-basics-javascript/framework?legacy-js-course=/crawling/exporting-data permanent; - rewrite ^/academy/web-scraping-for-beginners/crawling/filtering-links$ /academy/scraping-basics-javascript/getting-links?legacy-js-course=/crawling/filtering-links permanent; - rewrite ^/academy/web-scraping-for-beginners/crawling/finding-links$ /academy/scraping-basics-javascript/getting-links?legacy-js-course=/crawling/finding-links permanent; - rewrite ^/academy/web-scraping-for-beginners/crawling/first-crawl$ /academy/scraping-basics-javascript/crawling?legacy-js-course=/crawling/first-crawl permanent; - rewrite ^/academy/web-scraping-for-beginners/crawling/headless-browser$ /academy/scraping-basics-javascript?legacy-js-course=/crawling/headless-browser permanent; - rewrite ^/academy/web-scraping-for-beginners/crawling/pro-scraping$ /academy/scraping-basics-javascript/framework?legacy-js-course=/crawling/pro-scraping permanent; - rewrite ^/academy/web-scraping-for-beginners/crawling/recap-extraction-basics$ /academy/scraping-basics-javascript/extracting-data?legacy-js-course=/crawling/recap-extraction-basics permanent; - rewrite ^/academy/web-scraping-for-beginners/crawling/relative-urls$ /academy/scraping-basics-javascript/getting-links?legacy-js-course=/crawling/relative-urls permanent; - rewrite ^/academy/web-scraping-for-beginners/crawling/scraping-the-data$ /academy/scraping-basics-javascript/scraping-variants?legacy-js-course=/crawling/scraping-the-data permanent; - rewrite ^/academy/web-scraping-for-beginners/crawling$ /academy/scraping-basics-javascript/crawling?legacy-js-course=/crawling permanent; - rewrite ^/academy/web-scraping-for-beginners/data-extraction/browser-devtools$ /academy/scraping-basics-javascript/devtools-inspecting?legacy-js-course=/data-extraction/browser-devtools permanent; - rewrite ^/academy/web-scraping-for-beginners/data-extraction/computer-preparation$ /academy/scraping-basics-javascript/downloading-html?legacy-js-course=/data-extraction/computer-preparation permanent; - rewrite ^/academy/web-scraping-for-beginners/data-extraction/devtools-continued$ /academy/scraping-basics-javascript/devtools-extracting-data?legacy-js-course=/data-extraction/devtools-continued permanent; - rewrite ^/academy/web-scraping-for-beginners/data-extraction/node-continued$ /academy/scraping-basics-javascript/extracting-data?legacy-js-course=/data-extraction/node-continued permanent; - rewrite ^/academy/web-scraping-for-beginners/data-extraction/node-js-scraper$ /academy/scraping-basics-javascript/downloading-html?legacy-js-course=/data-extraction/node-js-scraper permanent; - rewrite ^/academy/web-scraping-for-beginners/data-extraction/project-setup$ /academy/scraping-basics-javascript/downloading-html?legacy-js-course=/data-extraction/project-setup permanent; - rewrite ^/academy/web-scraping-for-beginners/data-extraction/save-to-csv$ /academy/scraping-basics-javascript/saving-data?legacy-js-course=/data-extraction/save-to-csv permanent; - rewrite ^/academy/web-scraping-for-beginners/data-extraction/using-devtools$ /academy/scraping-basics-javascript/devtools-locating-elements?legacy-js-course=/data-extraction/using-devtools permanent; - rewrite ^/academy/web-scraping-for-beginners/data-extraction$ /academy/scraping-basics-javascript/devtools-inspecting?legacy-js-course=/data-extraction permanent; - rewrite ^/academy/web-scraping-for-beginners$ /academy/scraping-basics-javascript?legacy-js-course=/ permanent; + rewrite ^/academy/web-scraping-for-beginners/best-practices$ /academy/scraping-basics-javascript permanent; + rewrite ^/academy/web-scraping-for-beginners/introduction$ /academy/scraping-basics-javascript permanent; + rewrite ^/academy/web-scraping-for-beginners/challenge/initializing-and-setting-up$ /academy/expert-scraping-with-apify permanent; + rewrite ^/academy/web-scraping-for-beginners/challenge/modularity$ /academy/expert-scraping-with-apify permanent; + rewrite ^/academy/web-scraping-for-beginners/challenge/scraping-amazon$ /academy/expert-scraping-with-apify permanent; + rewrite ^/academy/web-scraping-for-beginners/challenge$ /academy/expert-scraping-with-apify permanent; + rewrite ^/academy/web-scraping-for-beginners/crawling/exporting-data$ /academy/scraping-basics-javascript/framework permanent; + rewrite ^/academy/web-scraping-for-beginners/crawling/filtering-links$ /academy/scraping-basics-javascript/getting-links permanent; + rewrite ^/academy/web-scraping-for-beginners/crawling/finding-links$ /academy/scraping-basics-javascript/getting-links permanent; + rewrite ^/academy/web-scraping-for-beginners/crawling/first-crawl$ /academy/scraping-basics-javascript/crawling permanent; + rewrite ^/academy/web-scraping-for-beginners/crawling/headless-browser$ /academy/puppeteer-playwright permanent; + rewrite ^/academy/web-scraping-for-beginners/crawling/pro-scraping$ /academy/scraping-basics-javascript/framework permanent; + rewrite ^/academy/web-scraping-for-beginners/crawling/recap-extraction-basics$ /academy/scraping-basics-javascript/extracting-data permanent; + rewrite ^/academy/web-scraping-for-beginners/crawling/relative-urls$ /academy/scraping-basics-javascript/getting-links permanent; + rewrite ^/academy/web-scraping-for-beginners/crawling/scraping-the-data$ /academy/scraping-basics-javascript/crawling permanent; + rewrite ^/academy/web-scraping-for-beginners/crawling$ /academy/scraping-basics-javascript/crawling permanent; + rewrite ^/academy/web-scraping-for-beginners/data-extraction/browser-devtools$ /academy/scraping-basics-javascript/devtools-inspecting permanent; + rewrite ^/academy/web-scraping-for-beginners/data-extraction/computer-preparation$ /academy/scraping-basics-javascript/downloading-html permanent; + rewrite ^/academy/web-scraping-for-beginners/data-extraction/devtools-continued$ /academy/scraping-basics-javascript/devtools-extracting-data permanent; + rewrite ^/academy/web-scraping-for-beginners/data-extraction/node-continued$ /academy/scraping-basics-javascript/extracting-data permanent; + rewrite ^/academy/web-scraping-for-beginners/data-extraction/node-js-scraper$ /academy/scraping-basics-javascript/downloading-html permanent; + rewrite ^/academy/web-scraping-for-beginners/data-extraction/project-setup$ /academy/scraping-basics-javascript/downloading-html permanent; + rewrite ^/academy/web-scraping-for-beginners/data-extraction/save-to-csv$ /academy/scraping-basics-javascript/saving-data permanent; + rewrite ^/academy/web-scraping-for-beginners/data-extraction/using-devtools$ /academy/scraping-basics-javascript/devtools-locating-elements permanent; + rewrite ^/academy/web-scraping-for-beginners/data-extraction$ /academy/scraping-basics-javascript/devtools-inspecting permanent; + rewrite ^/academy/web-scraping-for-beginners$ /academy/scraping-basics-javascript permanent; + + # Academy: removing the archived 'Web Scraping for Beginners' course + rewrite ^/academy/scraping-basics-javascript/legacy(\.md)?$ /academy/scraping-basics-javascript$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/introduction(\.md)?$ /academy/scraping-basics-javascript$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/best-practices(\.md)?$ /academy/scraping-basics-javascript$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/data-extraction(\.md)?$ /academy/scraping-basics-javascript/devtools-inspecting$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/data-extraction/browser-devtools(\.md)?$ /academy/scraping-basics-javascript/devtools-inspecting$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/data-extraction/using-devtools(\.md)?$ /academy/scraping-basics-javascript/devtools-locating-elements$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/data-extraction/devtools-continued(\.md)?$ /academy/scraping-basics-javascript/devtools-extracting-data$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/data-extraction/computer-preparation(\.md)?$ /academy/scraping-basics-javascript/downloading-html$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/data-extraction/project-setup(\.md)?$ /academy/scraping-basics-javascript/downloading-html$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/data-extraction/node-js-scraper(\.md)?$ /academy/scraping-basics-javascript/downloading-html$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/data-extraction/node-continued(\.md)?$ /academy/scraping-basics-javascript/extracting-data$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/data-extraction/save-to-csv(\.md)?$ /academy/scraping-basics-javascript/saving-data$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/crawling(\.md)?$ /academy/scraping-basics-javascript/crawling$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/crawling/recap-extraction-basics(\.md)?$ /academy/scraping-basics-javascript/extracting-data$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/crawling/finding-links(\.md)?$ /academy/scraping-basics-javascript/getting-links$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/crawling/filtering-links(\.md)?$ /academy/scraping-basics-javascript/getting-links$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/crawling/relative-urls(\.md)?$ /academy/scraping-basics-javascript/getting-links$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/crawling/first-crawl(\.md)?$ /academy/scraping-basics-javascript/crawling$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/crawling/scraping-the-data(\.md)?$ /academy/scraping-basics-javascript/crawling$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/crawling/headless-browser(\.md)?$ /academy/puppeteer-playwright$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/crawling/pro-scraping(\.md)?$ /academy/scraping-basics-javascript/framework$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/crawling/exporting-data(\.md)?$ /academy/scraping-basics-javascript/framework$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/challenge(\.md)?$ /academy/expert-scraping-with-apify$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/challenge/initializing-and-setting-up(\.md)?$ /academy/expert-scraping-with-apify$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/challenge/modularity(\.md)?$ /academy/expert-scraping-with-apify$1 permanent; + rewrite ^/academy/scraping-basics-javascript/legacy/challenge/scraping-amazon(\.md)?$ /academy/expert-scraping-with-apify$1 permanent; # Removed pages # GPT plugins were discontinued April 9th, 2024 - https://help.openai.com/en/articles/8988022-winding-down-the-chatgpt-plugins-beta diff --git a/scripts/joinLlmsFiles.mjs b/scripts/joinLlmsFiles.mjs index f739b6671d..8924c94ee8 100644 --- a/scripts/joinLlmsFiles.mjs +++ b/scripts/joinLlmsFiles.mjs @@ -59,9 +59,6 @@ const LLMS_INDEX_EXCLUDE_PATTERNS = [ '/api/v2/webhook-*', '/api/v2/webhooks-get', '/api/v2/webhooks-post', - // Academy: drop legacy JS course - '/academy/scraping-basics-javascript/legacy', - '/academy/scraping-basics-javascript/legacy/**', // Academy: drop individual Node.js tutorials (keep index) '/academy/node-js/*', // Academy: drop individual Python tutorials (keep index) diff --git a/sources/academy/webscraping/scraping_basics/_legacy.mdx b/sources/academy/webscraping/scraping_basics/_legacy.mdx deleted file mode 100644 index 9cb094131e..0000000000 --- a/sources/academy/webscraping/scraping_basics/_legacy.mdx +++ /dev/null @@ -1,6 +0,0 @@ - -:::caution Archived course - -This is an archive of our old course. Check out our new [Web scraping basics for JavaScript devs](/academy/scraping-basics-javascript) course instead! We plan to completely retire this old course in a few months. - -::: diff --git a/sources/academy/webscraping/scraping_basics_javascript/01_devtools_inspecting.md b/sources/academy/webscraping/scraping_basics_javascript/01_devtools_inspecting.md index e432224ee6..704eabf0a5 100644 --- a/sources/academy/webscraping/scraping_basics_javascript/01_devtools_inspecting.md +++ b/sources/academy/webscraping/scraping_basics_javascript/01_devtools_inspecting.md @@ -6,11 +6,8 @@ slug: /scraping-basics-javascript/devtools-inspecting pagination: true --- -import LegacyJsCourseAdmonition from '@site/src/components/LegacyJsCourseAdmonition'; import Exercises from '../scraping_basics/_exercises.mdx'; - - **In this lesson we'll use the browser tools for developers to inspect and manipulate the structure of a website.** --- diff --git a/sources/academy/webscraping/scraping_basics_javascript/02_devtools_locating_elements.md b/sources/academy/webscraping/scraping_basics_javascript/02_devtools_locating_elements.md index 12b18c7fa4..1f7193022c 100644 --- a/sources/academy/webscraping/scraping_basics_javascript/02_devtools_locating_elements.md +++ b/sources/academy/webscraping/scraping_basics_javascript/02_devtools_locating_elements.md @@ -6,11 +6,8 @@ slug: /scraping-basics-javascript/devtools-locating-elements pagination: true --- -import LegacyJsCourseAdmonition from '@site/src/components/LegacyJsCourseAdmonition'; import Exercises from '../scraping_basics/_exercises.mdx'; - - **In this lesson we'll use the browser tools for developers to manually find products on an e-commerce website.** --- diff --git a/sources/academy/webscraping/scraping_basics_javascript/03_devtools_extracting_data.md b/sources/academy/webscraping/scraping_basics_javascript/03_devtools_extracting_data.md index 696c057482..5a66eaec9b 100644 --- a/sources/academy/webscraping/scraping_basics_javascript/03_devtools_extracting_data.md +++ b/sources/academy/webscraping/scraping_basics_javascript/03_devtools_extracting_data.md @@ -6,11 +6,8 @@ slug: /scraping-basics-javascript/devtools-extracting-data pagination: true --- -import LegacyJsCourseAdmonition from '@site/src/components/LegacyJsCourseAdmonition'; import Exercises from '../scraping_basics/_exercises.mdx'; - - **In this lesson we'll use the browser tools for developers to manually extract product data from an e-commerce website.** --- diff --git a/sources/academy/webscraping/scraping_basics_javascript/04_downloading_html.md b/sources/academy/webscraping/scraping_basics_javascript/04_downloading_html.md index 2e4e2b4d4a..e7dff9e368 100644 --- a/sources/academy/webscraping/scraping_basics_javascript/04_downloading_html.md +++ b/sources/academy/webscraping/scraping_basics_javascript/04_downloading_html.md @@ -7,12 +7,9 @@ pagination: true --- import CodeBlock from '@theme/CodeBlock'; -import LegacyJsCourseAdmonition from '@site/src/components/LegacyJsCourseAdmonition'; import Exercises from '../scraping_basics/_exercises.mdx'; import LegoExercise from '!!raw-loader!roa-loader!./exercises/lego.mjs'; - - **In this lesson we'll start building a Node.js application for watching prices. As a first step, we'll use the Fetch API to download HTML code of a product listing page.** --- diff --git a/sources/academy/webscraping/scraping_basics_javascript/05_parsing_html.md b/sources/academy/webscraping/scraping_basics_javascript/05_parsing_html.md index 9cfd87817b..c31cda58e9 100644 --- a/sources/academy/webscraping/scraping_basics_javascript/05_parsing_html.md +++ b/sources/academy/webscraping/scraping_basics_javascript/05_parsing_html.md @@ -7,13 +7,10 @@ pagination: true --- import CodeBlock from '@theme/CodeBlock'; -import LegacyJsCourseAdmonition from '@site/src/components/LegacyJsCourseAdmonition'; import Exercises from '../scraping_basics/_exercises.mdx'; import F1AcademyTeamsExercise from '!!raw-loader!roa-loader!./exercises/f1academy_teams.mjs'; import F1AcademyDriversExercise from '!!raw-loader!roa-loader!./exercises/f1academy_drivers.mjs'; - - **In this lesson we'll look for products in the downloaded HTML. We'll use Cheerio to turn the HTML into objects which we can work with in our Node.js program.** --- diff --git a/sources/academy/webscraping/scraping_basics_javascript/06_locating_elements.md b/sources/academy/webscraping/scraping_basics_javascript/06_locating_elements.md index bb58ac8e50..0bfb839ed1 100644 --- a/sources/academy/webscraping/scraping_basics_javascript/06_locating_elements.md +++ b/sources/academy/webscraping/scraping_basics_javascript/06_locating_elements.md @@ -7,14 +7,11 @@ pagination: true --- import CodeBlock from '@theme/CodeBlock'; -import LegacyJsCourseAdmonition from '@site/src/components/LegacyJsCourseAdmonition'; import Exercises from '../scraping_basics/_exercises.mdx'; import ImoCountriesExercise from '!!raw-loader!roa-loader!./exercises/imo_countries.mjs'; import ImoCountriesSingleSelectorExercise from '!!raw-loader!roa-loader!./exercises/imo_countries_single_selector.mjs'; import GuardianF1TitlesExercise from '!!raw-loader!roa-loader!./exercises/guardian_f1_titles.mjs'; - - **In this lesson we'll locate product data in the downloaded HTML. We'll use Cheerio to find those HTML elements which contain details about each product, such as title or price.** --- diff --git a/sources/academy/webscraping/scraping_basics_javascript/07_extracting_data.md b/sources/academy/webscraping/scraping_basics_javascript/07_extracting_data.md index f4a725b4fb..ffb026f7fb 100644 --- a/sources/academy/webscraping/scraping_basics_javascript/07_extracting_data.md +++ b/sources/academy/webscraping/scraping_basics_javascript/07_extracting_data.md @@ -7,14 +7,11 @@ pagination: true --- import CodeBlock from '@theme/CodeBlock'; -import LegacyJsCourseAdmonition from '@site/src/components/LegacyJsCourseAdmonition'; import Exercises from '../scraping_basics/_exercises.mdx'; import IkeaDimensionsExercise from '!!raw-loader!roa-loader!./exercises/ikea_dimensions.mjs'; import IkeaDimensionsRegexExercise from '!!raw-loader!roa-loader!./exercises/ikea_dimensions_regex.mjs'; import GuardianPublishDatesExercise from '!!raw-loader!roa-loader!./exercises/guardian_publish_dates.mjs'; - - **In this lesson we'll finish extracting product data from the downloaded HTML. With help of basic string manipulation we'll focus on cleaning and correctly representing the product price.** --- diff --git a/sources/academy/webscraping/scraping_basics_javascript/08_saving_data.md b/sources/academy/webscraping/scraping_basics_javascript/08_saving_data.md index 70358c5662..3d3fab727d 100644 --- a/sources/academy/webscraping/scraping_basics_javascript/08_saving_data.md +++ b/sources/academy/webscraping/scraping_basics_javascript/08_saving_data.md @@ -7,11 +7,8 @@ pagination: true --- import CodeBlock from '@theme/CodeBlock'; -import LegacyJsCourseAdmonition from '@site/src/components/LegacyJsCourseAdmonition'; import ProcessProductsJsonExercise from '!!raw-loader!roa-loader!./exercises/process_products_json.mjs'; - - **In this lesson, we'll save the data we scraped in the popular formats, such as CSV or JSON. We'll use the json2csv library to export the files.** --- diff --git a/sources/academy/webscraping/scraping_basics_javascript/09_getting_links.md b/sources/academy/webscraping/scraping_basics_javascript/09_getting_links.md index 15a4d6e597..79e0fa98f2 100644 --- a/sources/academy/webscraping/scraping_basics_javascript/09_getting_links.md +++ b/sources/academy/webscraping/scraping_basics_javascript/09_getting_links.md @@ -7,13 +7,10 @@ pagination: true --- import CodeBlock from '@theme/CodeBlock'; -import LegacyJsCourseAdmonition from '@site/src/components/LegacyJsCourseAdmonition'; import Exercises from '../scraping_basics/_exercises.mdx'; import WtaTennisLinksExercise from '!!raw-loader!roa-loader!./exercises/wta_tennis_links.mjs'; import GuardianF1LinksExercise from '!!raw-loader!roa-loader!./exercises/guardian_f1_links.mjs'; - - **In this lesson, we'll locate and extract links to individual product pages. We'll use Cheerio to find the relevant bits of HTML.** --- diff --git a/sources/academy/webscraping/scraping_basics_javascript/10_crawling.md b/sources/academy/webscraping/scraping_basics_javascript/10_crawling.md index c38355805c..a726ecf6c8 100644 --- a/sources/academy/webscraping/scraping_basics_javascript/10_crawling.md +++ b/sources/academy/webscraping/scraping_basics_javascript/10_crawling.md @@ -7,13 +7,10 @@ pagination: true --- import CodeBlock from '@theme/CodeBlock'; -import LegacyJsCourseAdmonition from '@site/src/components/LegacyJsCourseAdmonition'; import Exercises from '../scraping_basics/_exercises.mdx'; import WtaTennisPlayersExercise from '!!raw-loader!roa-loader!./exercises/wta_tennis_players.mjs'; import GuardianF1AuthorsExercise from '!!raw-loader!roa-loader!./exercises/guardian_f1_authors.mjs'; - - **In this lesson, we'll follow links to individual product pages. We'll use the Fetch API to download them and Cheerio to process them.** --- diff --git a/sources/academy/webscraping/scraping_basics_javascript/11_scraping_variants.md b/sources/academy/webscraping/scraping_basics_javascript/11_scraping_variants.md index fcca22a7dd..7758f084b5 100644 --- a/sources/academy/webscraping/scraping_basics_javascript/11_scraping_variants.md +++ b/sources/academy/webscraping/scraping_basics_javascript/11_scraping_variants.md @@ -7,13 +7,10 @@ pagination: true --- import CodeBlock from '@theme/CodeBlock'; -import LegacyJsCourseAdmonition from '@site/src/components/LegacyJsCourseAdmonition'; import Exercises from '../scraping_basics/_exercises.mdx'; import JsLlmProjectsExercise from '!!raw-loader!roa-loader!./exercises/js_llm_projects.mjs'; import EurozonePopulationExercise from '!!raw-loader!roa-loader!./exercises/eurozone_population.mjs'; - - **In this lesson, we'll scrape the product detail pages to represent each product variant as a separate item in our dataset.** --- diff --git a/sources/academy/webscraping/scraping_basics_javascript/12_framework.md b/sources/academy/webscraping/scraping_basics_javascript/12_framework.md index f1cb07f02b..4b0ef84934 100644 --- a/sources/academy/webscraping/scraping_basics_javascript/12_framework.md +++ b/sources/academy/webscraping/scraping_basics_javascript/12_framework.md @@ -7,13 +7,10 @@ pagination: true --- import CodeBlock from '@theme/CodeBlock'; -import LegacyJsCourseAdmonition from '@site/src/components/LegacyJsCourseAdmonition'; import Exercises from '../scraping_basics/_exercises.mdx'; import CrawleeF1DriversExercise from '!!raw-loader!roa-loader!./exercises/crawlee_f1_drivers.mjs'; import CrawleeNetflixRatingsExercise from '!!raw-loader!roa-loader!./exercises/crawlee_netflix_ratings.mjs'; - - **In this lesson, we'll rework our application for watching prices so that it builds on top of a scraping framework. We'll use Crawlee to make the program simpler, faster, and more robust.** --- diff --git a/sources/academy/webscraping/scraping_basics_javascript/13_platform.md b/sources/academy/webscraping/scraping_basics_javascript/13_platform.md index dc9e202ff7..a405220289 100644 --- a/sources/academy/webscraping/scraping_basics_javascript/13_platform.md +++ b/sources/academy/webscraping/scraping_basics_javascript/13_platform.md @@ -6,9 +6,6 @@ slug: /scraping-basics-javascript/platform pagination: true --- -import LegacyJsCourseAdmonition from '@site/src/components/LegacyJsCourseAdmonition'; - - **In this lesson, we'll deploy our application to a scraping platform that automatically runs it daily. We'll also use the platform's API to retrieve and work with the results.** diff --git a/sources/academy/webscraping/scraping_basics_javascript/index.md b/sources/academy/webscraping/scraping_basics_javascript/index.md index 4b96daf9ec..57286418b8 100644 --- a/sources/academy/webscraping/scraping_basics_javascript/index.md +++ b/sources/academy/webscraping/scraping_basics_javascript/index.md @@ -9,9 +9,6 @@ pagination: true --- import DocCardList from '@theme/DocCardList'; -import LegacyJsCourseAdmonition from '@site/src/components/LegacyJsCourseAdmonition'; - - **Learn how to use JavaScript to extract information from websites in this practical course, starting from the absolute basics.** diff --git a/sources/academy/webscraping/scraping_basics_legacy/best_practices.md b/sources/academy/webscraping/scraping_basics_legacy/best_practices.md deleted file mode 100644 index ae3dd8bb67..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/best_practices.md +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Best practices when writing scrapers -description: Understand the standards and best practices that we here at Apify abide by to write readable, scalable, and maintainable code. -sidebar_position: 1.5 -slug: /scraping-basics-javascript/legacy/best-practices -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../scraping_basics/_legacy.mdx'; - -**Understand the standards and best practices that we here at Apify abide by to write readable, scalable, and maintainable code.** - - - ---- - -Every developer has their own style, which evolves as they grow and learn. While one dev might prefer a more [functional](https://en.wikipedia.org/wiki/Functional_programming) style, another might find an [imperative](https://en.wikipedia.org/wiki/Imperative_programming) approach to be more intuitive. We at Apify understand this, and have written this best practices lesson with that in mind. - -The goal of this lesson is not to force you into a specific paradigm or to make you think that you're doing things wrong, but instead to provide you some insight into the standards and best practices that we at Apify follow to ensure readable, maintainable, scalable code. - -## Code style {#code-style} - -When it comes to your code style when writing scrapers, there are some general things we recommend. - -### Clean code {#clean-code} - -Praise [clean code](https://blog.risingstack.com/javascript-clean-coding-best-practices-node-js-at-scale/)! Use proper variable and function names that are descriptive of what they are, and split your code into smaller [pure](https://en.wikipedia.org/wiki/Pure_function) functions. - -### Constant variables {#constants} - -Define any [constant variables](https://softwareengineering.stackexchange.com/questions/250619/best-practices-reasons-for-string-constants-in-javascript) that globally apply to the scraper in a single file named **constants.js**, from where they will all be imported. Constant variable names should be in `UPPERCASE_WITH_UNDERSCORES` style. - -> If you have a whole lot of constant variables, they can be in a folder named **constants** organized into different files. - -### Use ES6 JavaScript {#use-es6} - -If you're writing your scraper in JavaScript, use [ES6](https://www.w3schools.com/js/js_es6.asp) features and ditch the old ones which they replace. This means using `const` and `let` instead of `var`, `includes` instead of `indexOf`, etc. - -> To learn more about some of the most popular (and awesome) ES6+ features, check out [this](https://medium.com/@matthiasvstephens/why-is-es6-so-awesome-88bff6857849) article. - -### No magic numbers {#no-magic-numbers} - -Avoid using [magic numbers](https://en.wikipedia.org/wiki/Magic_number_(programming)) as much as possible. Either declare them as a **constant** variable in your **constants.js** file, or if they are only used once, add a comment explaining what the number is. - -Don't write code like this: - -```js -const x = (y) => (y - 32) * (5 / 9); -``` - -That is quite confusing due to the nondescriptive naming and the magic numbers. Do this instead: - -```js -// Converts a fahrenheit value to celsius -const fahrenheitToCelsius = (celsius) => (celsius - 32) * (5 / 9); -``` - -### Use comments! {#use-comments} - -Don't be shy to add comments to your code! Even when using descriptive function and variable naming, it might still be a good idea to add a comment in places where you had to make a tough decision or chose an unusual choice. - -> If you're a true pro, use [JSDoc](https://jsdoc.app/) to comment and document your code. - -## Logging {#logging} - -Logging helps you understand exactly what your scraper is doing. Generally, having more logs is better than having fewer. Especially make sure to log your `catch` blocks - no error should pass unseen unless there is a good reason. - -For scrapers that will run longer than usual, keep track of some useful stats (such as **itemsScraped** or **errorsHit**) and log them to the console on an interval. - -The meaning of your log messages should make sense to an outsider who is not familiar with the inner workings of your scraper. Avoid log lines with just numbers or just URLs - always identify what the number/string means. - -Here is an example of an "incorrect" log message: - -```text -300 https://example.com/1234 1234 -``` - -And here is that log message translated into something that makes much more sense to the end user: - -```text -Index 1234 --- https://example.com/1234 --- took 300 ms -``` - -## Input {#input} - -When it comes to accepting input into a scraper, two main best practices should be followed. - -### Set limits {#set-limits} - -When allowing your users to pass input properties which could break the scraper (such as **timeout** set to **0**), be sure to disallow ridiculous values. Set a maximum/minimum number allowed, maximum array input length, etc. - -### Validate {#validate} - -Validate the input provided by the user! This should be the very first thing your scraper does. If the fields in the input are missing or in an incorrect type/format, either parse the value and correct it programmatically or throw an informative error telling the user how to fix the error. - -> On the Apify platform, you can use the [input schema](../../platform/deploying_your_code/input_schema.md) to both validate inputs and generate a clean UI for those using your scraper. - -## Error handling {#error-handling} - -Errors are bound to occur in scrapers. Perhaps it got blocked, or perhaps the data scraped was corrupted in some way. - -Whatever the reason, a scraper shouldn't completely crash when an error occurs. Use `try...catch` blocks to catch errors and log useful messages. The log messages should indicate where the error happened, and what type of error happened. - -Bad error log message: - -```text -Cannot read property โ€œ0โ€ from undefined -``` - -Good error log message: - -```text -Could not parse an address, skipping the page. Url: https://www.example-website.com/people/1234 -``` - -This doesn't mean that you should absolutely litter your code with `try...catch` blocks, but it does mean that they should be placed in error-prone areas (such as API calls or testing a string with a specific regular expression). - -> If the error that has occurred renders that run of the scraper completely useless, exit the process immediately. - -Logging is the minimum you should be doing though. For example, if you have an entire object of scraped data and just the **price** field fails to be parsed, you might not want to throw away the rest of that data. Rather, it could still be pushed to the output and a log message like this could appear: - -```text -We could not parse the price of product: Men's Trainers Orange, pushing anyways. -``` - -This really depends on your use case though. If you want 100% clean data, you might not want to push incomplete objects and just retry (ideally) or log an error message instead. - -## Recap {#recap} - -Wow, that's a whole lot of things to abide by! How will you remember all of them? Try to follow these three points: - -1. Describe your code as you write it with good naming, constants, and comments. It **should read like a book**. -2. Add log messages at points throughout your code so that when it's running, you (and everyone else) know what's going on. -3. Handle errors appropriately. Log the error and either retry, or continue on. Only throw if the error will be caught or if the error is absolutely detrimental to the scraper's run. diff --git a/sources/academy/webscraping/scraping_basics_legacy/challenge/images/crawlee-create.png b/sources/academy/webscraping/scraping_basics_legacy/challenge/images/crawlee-create.png deleted file mode 100644 index b59fac16d8..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/challenge/images/crawlee-create.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/challenge/images/offers-page.jpg b/sources/academy/webscraping/scraping_basics_legacy/challenge/images/offers-page.jpg deleted file mode 100644 index 73f2448e64..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/challenge/images/offers-page.jpg and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/challenge/images/product-offers.webp b/sources/academy/webscraping/scraping_basics_legacy/challenge/images/product-offers.webp deleted file mode 100644 index 9b9337884d..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/challenge/images/product-offers.webp and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/challenge/images/result-items.webp b/sources/academy/webscraping/scraping_basics_legacy/challenge/images/result-items.webp deleted file mode 100644 index d57aa80237..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/challenge/images/result-items.webp and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/challenge/images/view-offers-button.jpg b/sources/academy/webscraping/scraping_basics_legacy/challenge/images/view-offers-button.jpg deleted file mode 100644 index 4144858d58..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/challenge/images/view-offers-button.jpg and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/challenge/index.md b/sources/academy/webscraping/scraping_basics_legacy/challenge/index.md deleted file mode 100644 index 2a38805be4..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/challenge/index.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Challenge -description: Test your knowledge acquired in the previous sections of this course by building an Amazon scraper using Crawlee's CheerioCrawler! -sidebar_position: 1.4 -slug: /scraping-basics-javascript/legacy/challenge -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Test your knowledge acquired in the previous sections of this course by building an Amazon scraper using Crawlee's CheerioCrawler!** - - - ---- - -Before moving onto the other courses in the academy, we recommend following along with this section, as it combines everything you've learned in the previous lessons into one cohesive project that helps you prove to yourself that you've thoroughly understood the material. - -We recommend that you make sure you've gone through both the [data extraction](../data_extraction/index.md) and [crawling](../crawling/index.md) sections of this course to ensure the smoothest development process. - -## Learning ๐Ÿง  {#learning} - -Before continuing, it is highly recommended to do the following: - -- Look over [how to build a crawler in Crawlee](https://crawlee.dev/docs/introduction/first-crawler) and ideally **code along**. -- Read [this short article](https://docs.apify.com/academy/node-js/request-labels-in-apify-actors) about [**request labels**](https://crawlee.dev/api/core/class/Request#label) (this will be extremely useful later on). -- Check out [this tutorial](../../../tutorials/node_js/dealing_with_dynamic_pages.md) about dynamic pages. -- Read about the [RequestQueue](https://crawlee.dev/api/core/class/RequestQueue). - -## Our task {#our-task} - -On Amazon, we can use this link to get to the results page of any product we want: - -```text -https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=KEYWORD -``` - -Our crawler's input will look like this: - -```json -{ - "keyword": "iphone" -} -``` - -The goal at hand is to scrape all of the products from the first page of results for whatever keyword was provided (for our test case, it will be **iPhone**), then to scrape all available offers of each product and push the results to the dataset. For context, the offers for a product look like this: - -![Amazon product offers](./images/product-offers.webp) - -In the end, we'd like our final output to look something like this: - -```json -[ - { - "title": "Apple iPhone 6 a1549 16GB Space Gray Unlocked (Certified Refurbished)", - "asin": "B07P6Y7954", - "itemUrl": "https://www.amazon.com/Apple-iPhone-Unlocked-Certified-Refurbished/dp/B00YD547Q6/ref=sr_1_2?s=wireless&ie=UTF8&qid=1539772626&sr=1-2&keywords=iphone", - "description": "What's in the box: Certified Refurbished iPhone 6 Space Gray 16GB Unlocked , USB Cable/Adapter. Comes in a Generic Box with a 1 Year Limited Warranty.", - "keyword": "iphone", - "sellerName": "Blutek Intl", - "offer": "$162.97" - }, - { - "title": "Apple iPhone 6 a1549 16GB Space Gray Unlocked (Certified Refurbished)", - "asin": "B07P6Y7954", - "itemUrl": "https://www.amazon.com/Apple-iPhone-Unlocked-Certified-Refurbished/dp/B00YD547Q6/ref=sr_1_2?s=wireless&ie=UTF8&qid=1539772626&sr=1-2&keywords=iphone", - "description": "What's in the box: Certified Refurbished iPhone 6 Space Gray 16GB Unlocked , USB Cable/Adapter. Comes in a Generic Box with a 1 Year Limited Warranty.", - "keyword": "iphone", - "sellerName": "PLATINUM DEALS", - "offer": "$169.98" - }, - { - "...": "..." - } -] - -``` - -> The `asin` is the ID of the product, which is data present on the Amazon website. - -Each of the items in the dataset will represent a scraped offer and will have the same `title`, `asin`, `itemUrl`, and `description`. The offer-specific fields will be `sellerName` and `offer`. - - - -## First up {#next} - -From this course, you should have all the knowledge to build this scraper by yourself. Give it a try, then come back to compare your scraper with our solution. - -The challenge can be completed using either [CheerioCrawler](https://crawlee.dev/api/cheerio-crawler/class/CheerioCrawler) or [PlaywrightCrawler](https://crawlee.dev/api/playwright-crawler/class/PlaywrightCrawler). Playwright is significantly slower but doesn't get blocked as much. You will learn the most by implementing both. - -Let's start off this section by [initializing and setting up](./initializing_and_setting_up.md) our project with the Crawlee CLI (don't worry, no additional installation is required). diff --git a/sources/academy/webscraping/scraping_basics_legacy/challenge/initializing_and_setting_up.md b/sources/academy/webscraping/scraping_basics_legacy/challenge/initializing_and_setting_up.md deleted file mode 100644 index b01c833515..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/challenge/initializing_and_setting_up.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Initialization and setting up -description: When you extract links from a web page, you often end up with a lot of irrelevant URLs. Learn how to filter the links to only keep the ones you need. -sidebar_position: 1 -slug: /scraping-basics-javascript/legacy/challenge/initializing-and-setting-up -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**When you extract links from a web page, you often end up with a lot of irrelevant URLs. Learn how to filter the links to only keep the ones you need.** - - - ---- - -The Crawlee CLI speeds up the process of setting up a Crawlee project. Navigate to the directory you'd like your project's folder to live, then open up a terminal instance and run the following command: - -```shell -npx crawlee create amazon-crawler -``` - -Once you run this command, you'll get prompted into a menu which you can navigate using your arrow keys. Each of these options will generate a different boilerplate code when selected. We're going to work with CheerioCrawler today, so we'll select the **CheerioCrawler template project** template, and then press **Enter**. - -![Crawlee CLI "create" command](./images/crawlee-create.png) - -Once it's completed, open up the **amazon-crawler** folder that was generated by the `npx crawlee create` command. We're going to modify the **main.js** boilerplate to fit our needs: - -```js -// main.js -import { CheerioCrawler, KeyValueStore, log } from 'crawlee'; -import { router } from './routes.js'; - -// Grab our keyword from the input -const { keyword } = await KeyValueStore.getInput(); - -const crawler = new CheerioCrawler({ - requestHandler: router, - - // If you have access to Apify Proxy, you can use residential proxies and - // high retry count which helps with blocking - // If you don't, your local IP address will likely be fine for a few requests if you scrape slowly. - // proxyConfiguration: await Actor.createProxyConfiguration({ groups: ['RESIDENTIAL'] }), - // maxRequestRetries: 10, -}); - -log.info('Starting the crawl.'); -await crawler.run([{ - // Turn the keyword into a link we can make a request with - url: `https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=${keyword}`, - label: 'START', - userData: { - keyword, - }, -}]); -log.info('Crawl finished.'); -``` - -```js -// routes.js -import { createCheerioRouter } from 'crawlee'; - -export const router = createCheerioRouter(); - -router.addDefaultHandler(({ log }) => { - log.info('Route reached.'); -}); -``` - -Finally, we'll add the following input file to **INPUT.json** in the project's root directory (next to `package.json`, `node_modules` and others) - -```json -{ - "keyword": "iphone" -} -``` - -> This is how we'll be inputting data into our scraper from now on. Don't worry though, from now on, we'll only need to work in the **main.js** and **routes.js** files! - -## Next up {#next} - -Cool! We're ready. But [let's discuss a bit about modularity](./modularity.md) before moving forward! diff --git a/sources/academy/webscraping/scraping_basics_legacy/challenge/modularity.md b/sources/academy/webscraping/scraping_basics_legacy/challenge/modularity.md deleted file mode 100644 index a7eaf8fd32..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/challenge/modularity.md +++ /dev/null @@ -1,134 +0,0 @@ ---- -title: Modularity -description: Before you build your first web scraper with Crawlee, it is important to understand the concept of modularity in programming. -sidebar_position: 2 -slug: /scraping-basics-javascript/legacy/challenge/modularity -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Before you build your first web scraper with Crawlee, it is important to understand the concept of modularity in programming.** - - - ---- - -Now that we've gotten our first request going, the first challenge is going to be selecting all of the resulting products on the page. Back in the browser, we'll use the DevTools hover tool to inspect a product. - -![Result products](./images/result-items.webp) - -**Bingo!** Each product seems to have a `data-asin` attribute, which includes the ASIN (product ID) data we want. Now, we can select each of these elements with this selector: `div > div[data-asin]:not([data-asin=""])`. Then, we'll scrape some data about each product, and push a request to the main product page so we can grab hold of the description. - -But, before we start scraping, let's pause to talk a bit about the important concept of **modularity**. You may have noticed the **src** folder inside of your project, which by default has a **routes.js** file in it. We're going to use this to create modularized functions which can then be conditionally executed by our crawler. - -```js -// routes.js -import { createCheerioRouter } from 'crawlee'; -import { BASE_URL } from './constants.js'; - -export const router = createCheerioRouter(); - -router.addDefaultHandler(({ log }) => { - log.info('Route reached.'); -}); - -// Add a handler to our router to handle requests with the 'START' label -router.addHandler('START', async ({ $, crawler, request }) => { - const { keyword } = request.userData; - - const products = $('div > div[data-asin]:not([data-asin=""])'); - - // loop through the resulting products - for (const product of products) { - const element = $(product); - const titleElement = $(element.find('.a-text-normal[href]')); - - const url = `${BASE_URL}${titleElement.attr('href')}`; - - // scrape some data from each and to a request - // to the crawler for its page - await crawler.addRequests([{ - url, - label: 'PRODUCT', - userData: { - // Pass the scraped data about the product to the next - // request so that it can be used there - data: { - title: titleElement.first().text().trim(), - asin: element.attr('data-asin'), - itemUrl: url, - keyword, - }, - }, - }]); - } -}); - -router.addHandler('PRODUCT', ({ log }) => log.info('on a product page!')); -``` - -Also notice that we are importing `BASE_URL` from **constants.js**. Here is what that file looks like: - -```js -// constants.js -export const BASE_URL = 'https://www.amazon.com'; -``` - -And here is what our **main.js** file currently looks like: - -```js -// main.js -import { CheerioCrawler, log, KeyValueStore } from 'crawlee'; -import { router } from './routes.js'; -import { BASE_URL } from './constants.js'; - -const { keyword = 'iphone' } = (await KeyValueStore.getInput()) ?? {}; - -const crawler = new CheerioCrawler({ - requestHandler: router, -}); - -await crawler.addRequests([ - { - // Use BASE_URL here instead - url: `${BASE_URL}/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=${keyword}`, - label: 'START', - userData: { - keyword, - }, - }, -]); - -log.info('Starting the crawl.'); -await crawler.run(); -log.info('Crawl finished.'); -``` - -One of the main reasons we **modularize** our code is to prevent massive and difficult to read files by separating concerns into separate files. In our **main.js** file, we're handling the initialization, configuration, and running of our crawler. In **routes.js**, we determine how the crawler should handle different routes, and in **constants.js** we define non-changing values that will be used throughout the project. - -Organized code makes everyone happy, including you - the one developing the scraper! Spaghetti is super awesome, [but not when it comes to programming](https://www.urbandictionary.com/define.php?term=spaghetti+code) ๐Ÿ - -This can even be optimized further by putting our `label` items into **constants.js**, like so: - -```js -// constants.js -export const BASE_URL = 'https://www.amazon.com'; - -export const labels = { - START: 'START', - PRODUCT: 'PRODUCT', - OFFERS: 'OFFERS', -}; -``` - -Then, the labels can be used by importing `labels` and accessing `labels.START`, `labels.PRODUCT`, or `labels.OFFERS`. - -This is not necessary, but it is best practice, as it can prevent dumb typos that can cause nasty bugs ๐Ÿž For the rest of this lesson, all of the examples using labels will be using the imported versions. - -> If you haven't already read the **Best practices** lesson in the **Web scraping basics for JavaScript devs** course, please [give it a read](../best_practices.md). - -## Next up {#next} - -Now that we've gotten that out of the way, we can finally continue with our Amazon scraper. [Let's do it](./scraping_amazon.md)! diff --git a/sources/academy/webscraping/scraping_basics_legacy/challenge/scraping_amazon.md b/sources/academy/webscraping/scraping_basics_legacy/challenge/scraping_amazon.md deleted file mode 100644 index b325d8a104..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/challenge/scraping_amazon.md +++ /dev/null @@ -1,205 +0,0 @@ ---- -title: Scraping Amazon -description: Before you build your first web scraper with Crawlee, it is important to understand the concept of modularity in programming. -sidebar_position: 4 -slug: /scraping-basics-javascript/legacy/challenge/scraping-amazon -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Build your first web scraper with Crawlee. Let's extract product information from Amazon to give you an idea of what real-world scraping looks like.** - - - ---- - -In our quick chat about modularity, we finished the code for the results page and added a request for each product to the crawler's **RequestQueue**. Here, we need to scrape the description, so it shouldn't be too hard: - -```js -// routes.js - -// ... - -router.addHandler(labels.PRODUCT, async ({ $ }) => { - const element = $('div#productDescription'); - - const description = element.text().trim(); - - console.log(description); // works! -}); -``` - - -Great! But where do we go from here? We need to visit the product page and scrape the offer from there. - -:::note Why only one offer per product? - -Amazon product pages list a single featured offer in their static HTML. The full list of sellers is loaded separately by JavaScript after the page loads. CheerioCrawler can't see the list because it only fetches the raw HTML, without running JavaScript. - -If you need all seller offers, you have to use [PlaywrightCrawler](../../puppeteer_playwright/index.md), which runs a real browser and can wait for that content to load. For this course, scraping the featured offer is enough to cover the key concepts. - -::: - -We'll add a request to the product page for each product: - -```js -// routes.js - -// ... - -router.addHandler(labels.PRODUCT, async ({ $, crawler, request }) => { - const { data } = request.userData; - - const description = $('div#productDescription').text().trim(); - - await crawler.addRequests([{ - url: `${BASE_URL}/dp/${data.asin}?th=1&psc=1`, - label: labels.OFFERS, - userData: { - data: { - ...data, - description, - }, - }, - }]); -}); -``` - -Then we handle it in the OFFERS handler: - -```js -// routes.js - -router.addHandler(labels.OFFERS, async ({ $, request }) => { - const { data } = request.userData; - - const price = $('.a-price .a-offscreen').first().text().trim(); - const sellerName = $('#sellerProfileTriggerId, #merchant-info a').first().text().trim(); - - await Dataset.pushData({ - ...data, - sellerName, - offer: price, - }); -}); -``` - -## Final code {#final-code} - -That should be it! Let's make sure we've all got the same code: - -```js -// constants.js -export const BASE_URL = 'https://www.amazon.com'; - -export const labels = { - START: 'START', - PRODUCT: 'PRODUCT', - OFFERS: 'OFFERS', -}; -``` - -```js -// routes.js -import { createCheerioRouter, Dataset } from 'crawlee'; -import { BASE_URL, labels } from './constants'; - -export const router = createCheerioRouter(); - -router.addHandler(labels.START, async ({ $, crawler, request }) => { - const { keyword } = request.userData; - - const products = $('div > div[data-asin]:not([data-asin=""])'); - - for (const product of products) { - const element = $(product); - const titleElement = $(element.find('.a-text-normal[href]')); - - const url = `${BASE_URL}${titleElement.attr('href')}`; - - await crawler.addRequests([ - { - url, - label: labels.PRODUCT, - userData: { - data: { - title: titleElement.first().text().trim(), - asin: element.attr('data-asin'), - itemUrl: url, - keyword, - }, - }, - }, - ]); - } -}); - -router.addHandler(labels.PRODUCT, async ({ $, crawler, request }) => { - const { data } = request.userData; - - const description = $('div#productDescription').text().trim(); - - await crawler.addRequests([ - { - url: `${BASE_URL}/dp/${data.asin}?th=1&psc=1`, - label: labels.OFFERS, - userData: { - data: { - ...data, - description, - }, - }, - }, - ]); -}); - -router.addHandler(labels.OFFERS, async ({ $, request }) => { - const { data } = request.userData; - - const price = $('.a-price .a-offscreen').first().text().trim(); - const sellerName = $('#sellerProfileTriggerId, #merchant-info a').first().text().trim(); - - await Dataset.pushData({ - ...data, - sellerName, - offer: price, - }); -}); -``` - -```js -// main.js -import { CheerioCrawler, KeyValueStore, log } from 'crawlee'; -import { router } from './routes.js'; - -// Grab our keyword from the input -const { keyword = 'iphone' } = (await KeyValueStore.getInput()) ?? {}; - -const crawler = new CheerioCrawler({ - requestHandler: router, -}); - -// Add our initial requests -await crawler.addRequests([ - { - // Turn the inputted keyword into a link we can make a request with - url: `https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=${keyword}`, - label: 'START', - userData: { - keyword, - }, - }, -]); - -log.info('Starting the crawl.'); -await crawler.run(); -log.info('Crawl finished.'); -``` - -## Wrap up ๐Ÿ’ฅ {#wrap-up} - -Nice work! You've officially built your first scraper with Crawlee! You're now ready to take on the rest of the Apify Academy with confidence. - -For now, this is the last section of the **Web scraping basics for JavaScript devs** course. If you want to learn more about web scraping, we recommend checking venturing out and following the other lessons in the Academy. We will keep updating the Academy with more content regularly until we cover all the advanced and expert topics we promised at the beginning. diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/exporting_data.md b/sources/academy/webscraping/scraping_basics_legacy/crawling/exporting_data.md deleted file mode 100644 index d710409b13..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/crawling/exporting_data.md +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: Exporting data -description: Learn how to export the data you scraped using Crawlee to CSV or JSON. -sidebar_position: 9 -slug: /scraping-basics-javascript/legacy/crawling/exporting-data -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Learn how to export the data you scraped using Crawlee to CSV or JSON.** - - - ---- - -In the previous lessons, you learned that: - -1. You can use `Dataset.pushData()` to save data to the default dataset. -2. The default dataset files are saved in the `./storage/datasets/default` folder. - -But when we look inside the folder, we see that there are a lot of files, and we don't want to work with those manually. We can use the dataset itself to export the data. - -## Exporting data to CSV {#export-csv} - -Crawlee's `Dataset` provides a way to export all your scraped data into one big CSV file. You can then open it in Excel or any other data processor. To do that, you need to call [`Dataset.exportToCSV()`](https://crawlee.dev/api/core/class/Dataset#exportToCSV) after collecting all the data. That means, after your crawler run finishes. - -```js title=browser.js -// ... -await crawler.run(); -// Add this line to export to CSV. -await Dataset.exportToCSV('results'); -``` - -After you add this one line and run the code, you'll find your CSV with all the scraped products in here: - -```text -./storage/key-value-stores/default/results.csv -``` - -:::info Key-value store - -[Key-value store](https://crawlee.dev/docs/guides/result-storage#key-value-store) is another of Crawlee's storages. It's best for saving files like CSVs, PDFs or images, but also large JSONs or crawler statistics. - -::: - -## Exporting data to JSON {#export-json} - -Exporting to JSON is very similar to exporting to CSV, but we'll use a different function: [`Dataset.exportToJSON`](https://crawlee.dev/api/core/class/Dataset#exportToJSON). Exporting to JSON is useful when you don't want to work with each item separately, but would rather have one big JSON file with all the results. - -```js title=browser.js -// ... -await crawler.run(); -// Add this line to export to JSON. -await Dataset.exportToJSON('results'); -``` - -You will find the resulting JSON here: - -```text -./storage/key-value-stores/default/results.json -``` - -## Final scraper code {#filtering-data} - -```js title=browser.js -import { PlaywrightCrawler, Dataset } from 'crawlee'; - -const crawler = new PlaywrightCrawler({ - // We removed the headless: false option to hide the browser windows. - requestHandler: async ({ parseWithCheerio, request, enqueueLinks }) => { - console.log(`Fetching URL: ${request.url}`); - - if (request.label === 'start-url') { - await enqueueLinks({ - selector: 'a.product-item__title', - }); - return; - } - - // Fourth, parse the browser's page with Cheerio. - const $ = await parseWithCheerio(); - - const title = $('h1').text().trim(); - const vendor = $('a.product-meta__vendor').text().trim(); - const price = $('span.price').contents()[2].nodeValue; - const reviewCount = parseInt($('span.rating__caption').text(), 10); - const description = $('div[class*="description"] div.rte').text().trim(); - const recommendedProducts = $('.product-recommendations a.product-item__title') - .map((i, el) => $(el).text().trim()) - .toArray(); - - await Dataset.pushData({ - title, - vendor, - price, - reviewCount, - description, - recommendedProducts, - }); - }, -}); - -await crawler.addRequests([{ - url: 'https://warehouse-theme-metal.myshopify.com/collections/sales', - label: 'start-url', -}]); - -await crawler.run(); -await Dataset.exportToCSV('results'); -``` - -## Next up {#next} - -And this is it for the [**Basics of crawling**](./index.md) section of the [**Web scraping basics for JavaScript devs**](../index.md) course. If you want to learn more, test your knowledge of the methods and concepts you learned in this course by moving forward with the [**challenge**](../challenge/index.md). diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/filtering_links.md b/sources/academy/webscraping/scraping_basics_legacy/crawling/filtering_links.md deleted file mode 100644 index c87820d00d..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/crawling/filtering_links.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: Filtering links -description: When you extract links from a web page, you often end up with a lot of irrelevant URLs. Learn how to filter the links to only keep the ones you need. -sidebar_position: 3 -slug: /scraping-basics-javascript/legacy/crawling/filtering-links -pagination: true -noindex: true ---- - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**When you extract links from a web page, you often end up with a lot of irrelevant URLs. Learn how to filter the links to only keep the ones you need.** - - - ---- - -Web pages are full of links, but frankly, most of them are useless to us when scraping. Filtering links can be approached in two ways: Targeting the links we're interested in by using unique CSS selectors, or extracting all links and then using pattern matching to find the sought after URLs. In real scraping scenarios, both of these two approaches are often combined for the most effective URL filtering. - -## Filtering with unique CSS selectors {#css-filtering} - -In the previous lesson, we grabbed all the links from the HTML document. - - - - -```js -document.querySelectorAll('a'); -``` - - - - -```js -$('a'); -``` - - - - -### Attribute selector {#attribute-selector} - -That's not the only way to do it, however. Since we're interested in the `href` attributes, a first very reasonable filter is to exclusively target the `` tags that have the `href` attribute (yes, anchor tags without the attribute can and do exist). You can do that by using the [CSS attribute selector](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors). - - - - -```js -document.querySelectorAll('a[href]'); -``` - - - - -```js -$('a[href]'); -``` - - - - -Adding the `[href]` part of the selector will save you from nasty bug hunts on certain pages. - -### Link specific selectors {#specific-selectors} - -Let's go back to the [Sales category of Warehouse](https://warehouse-theme-metal.myshopify.com/collections/sales) and see how we could capture only the links to product detail pages. After inspecting the product cards in DevTools, you'll find that the links are available together with the product's title. Getting them will therefore be very similar to getting the product titles in the previous section. - -![product detail page link](./images/filtering-product-detail-link.png) - - - - -```js -document.querySelectorAll('a.product-item__title'); -``` - - - - -```js -$('a.product-item__title'); -``` - - - - - -When we print all the URLs in the DevTools console, we can see that we've correctly filtered only the product detail page URLs. - -```js title=DevTools -for (const a of document.querySelectorAll('a.product-item__title')) { - console.log(a.href); -} -``` - -:::info Relative links - -If you try this in Node.js instead of DevTools, you will not get the full URLs, but only so-called **relative links**. We will explain what those are and how to work with them in the next lesson. - -::: - -![Product URLs printed to console](./images/filtering-product-urls.png) - - -## Filtering with pattern-matching {#pattern-matching-filter} - -Another common way to filter links (or any text, really) is by matching patterns with regular expressions. - -> [Learn more about regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) - -When we inspect the product URLs, we'll find that they all look like the following: - -```text -https://warehouse-theme-metal.myshopify.com/products/denon-ah-c720-in-ear-headphones -https://warehouse-theme-metal.myshopify.com/products/sony-sacs9-10-inch-active-subwoofer -https://warehouse-theme-metal.myshopify.com/products/sony-ps-hx500-hi-res-usb-turntable -``` - -That is, they all begin with exactly the same pattern and only differ in the last portion of the path. We could write the pattern like this: - -```text -https://warehouse-theme-metal.myshopify.com/products/{PRODUCT_NAME} -``` - -This means that we can create a regular expression that matches those URLs. You can do it in many ways . For simplicity, let's go with this one: - -```RegExp -https?:\/\/warehouse-theme-metal\.myshopify\.com\/products\/[\w\-]+ -``` - -This regular expression matches all URLs that use either `http` or `https` protocol and point to `warehouse-theme-metal.myshopify.com/products/` immediately followed with any number of letters or dashes `-`. - -> A great way to learn more about regular expression syntax and to test your expressions are tools like [regex101.com](https://regex101.com/) or [regexr.com](https://regexr.com/). It's okay if you don't get the hang of it right away! - -To test our regular expression in the DevTools console, we'll first create a [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) object and then test the URLs with the [`regExp.test(string)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) function. - -```js -// To demonstrate pattern matching, we use only the 'a' -// selector to select all links on the page. -for (const a of document.querySelectorAll('a')) { - const regExp = /https?:\/\/warehouse-theme-metal\.myshopify\.com\/products\/[\w-]+/; - const url = a.href; - if (regExp.test(url)) console.log(url); -} -``` - -When you run this code in DevTools Console on the [Sales category of Warehouse](https://warehouse-theme-metal.myshopify.com/collections/sales), you'll see that it produces a slightly different set of URLs than the CSS filter did. - -![filtering-regex-urls.png](./images/filtering-regex-urls.png) - -That's because we selected all the links on the page and apparently there are more ways to get to the product detail pages. After careful inspection we can find that we can get there not only by clicking the title, but also by clicking the product's image, which leads to duplicates. Some products also have review links that lead to a specific subsection of the product detail page. - -With that said, yes, filtering with CSS selectors is often the better and more reliable option. But sometimes, it's not enough, and knowing about pattern matching with regular expressions expands your scraping toolbox and helps you tackle more complex scenarios. - -## Next Up {#next} - -In the [next lesson](./relative_urls.md) we'll see how rewriting this code to Node.js is not so simple and learn about absolute and relative URLs in the process. diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/finding_links.js b/sources/academy/webscraping/scraping_basics_legacy/crawling/finding_links.js deleted file mode 100644 index 9af7879a18..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/crawling/finding_links.js +++ /dev/null @@ -1,18 +0,0 @@ -import * as cheerio from 'cheerio'; -import { gotScraping } from 'got-scraping'; - -const storeUrl = 'https://warehouse-theme-metal.myshopify.com/collections/sales'; - -const response = await gotScraping(storeUrl); -const html = response.body; - -const $ = cheerio.load(html); - -// ------- new code below - -const links = $('a'); - -for (const link of links) { - const url = $(link).attr('href'); - console.log(url); -} diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/finding_links.md b/sources/academy/webscraping/scraping_basics_legacy/crawling/finding_links.md deleted file mode 100644 index 310365e155..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/crawling/finding_links.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Finding links -description: Learn what a link looks like in HTML and how to find and extract their URLs when web scraping. Using both DevTools and Node.js. -sidebar_position: 2 -slug: /scraping-basics-javascript/legacy/crawling/finding-links -pagination: true -noindex: true ---- - -import Example from '!!raw-loader!roa-loader!./finding_links.js'; -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Learn what a link looks like in HTML and how to find and extract their URLs when web scraping using both DevTools and Node.js.** - - - ---- - -Many kinds of links exist on the internet, and we'll cover all the types in the advanced Academy courses. For now, let's think of links as [HTML anchor elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a) with `` tags. A typical link looks like this: - -```HTML -This is a link to example.com -``` - -On a webpage, the link above will look like this: [This is a link to example.com](https://example.com) When you click it, your browser will navigate to the URL in the `` tag's `href` attribute (`https://example.com`). - -> `href` means **H**ypertext **REF**erence. You don't need to remember this - just know that `href` typically means some sort of link. - -## Extracting links ๐Ÿ”— {#extracting-links} - -If a link is an HTML element, and the URL is an attribute, this means that we can extract links the same way as we extracted data. To test this theory in the browser, we can try running the following code in our DevTools console on any website. - -```js -// Select all the elements. -const links = document.querySelectorAll('a'); -// For each of the links... -for (const link of links) { - // get the value of its 'href' attribute... - const url = link.href; - // and print it to console. - console.log(url); -} -``` - -Go to the [Warehouse store Sales category](https://warehouse-theme-metal.myshopify.com/collections/sales), open the DevTools Console, paste the above code and run it. - -![links extracted from Warehouse store](./images/warehouse-links.png) - -**_Boom_** ๐Ÿ’ฅ, all the links from the page have now been printed to the console. Most of the links point to other parts of the website, but some links lead to other domains like facebook.com or instagram.com. - -## Extracting link URLs in Node.js {#Extracting-links-in-node} - -DevTools Console is a fun playground, but Node.js is way more useful. Let's create a new file in our project called **crawler.js** and add some basic crawling code that prints all the links from the [Sales category of Warehouse](https://warehouse-theme-metal.myshopify.com/collections/sales). - -We'll start from a boilerplate that's very similar to the scraper we built in [Basics of data extraction](../data_extraction/node_js_scraper.md). - - - {Example} - - -Aside from importing libraries and downloading HTML, we load the HTML into Cheerio and then use it to retrieve all the `` elements. After that, we iterate over the collected links and print their `href` attributes, which we access using the [`.attr()`](https://cheerio.js.org/docs/api/classes/Cheerio#attr) method. - -When you run the above code, you'll see quite a lot of links in the terminal. Some of them may look wrong, because they don't start with the regular `https://` protocol. We'll learn what to do with them in the following lessons. - -## Next Up {#next} - -The [next lesson](./filtering_links.md) will teach you how to select and filter links, so that your crawler will always work only with valid and useful URLs. diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/first_crawl.md b/sources/academy/webscraping/scraping_basics_legacy/crawling/first_crawl.md deleted file mode 100644 index 2d12be2f12..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/crawling/first_crawl.md +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: Your first crawl -description: Learn how to crawl the web using Node.js, Cheerio and an HTTP client. Extract URLs from pages and use them to visit more websites. -sidebar_position: 5 -slug: /scraping-basics-javascript/legacy/crawling/first-crawl -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Learn how to crawl the web using Node.js, Cheerio and an HTTP client. Extract URLs from pages and use them to visit more websites.** - - - ---- - -In the previous lessons, we learned what crawling is and how to extract URLs from a page's HTML. The only thing that remains is to write the code - let's get right to it! - -> If the code starts to look too complex to you, don't worry. We're showing it for educational purposes, so that you can learn how crawling works. Near the end of this course, we'll show you a much easier and faster way to crawl, using a specialized scraping library. If you want, you can skip the details and [go there now](./pro_scraping.md). - -## Processing URLs {#processing-urls} - -In the previous lessons, we collected and filtered all the URLs pointing to individual products in the [Sales category of Warehouse store](https://warehouse-theme-metal.myshopify.com/collections/sales). To crawl the URLs, we must take the whole list we collected and download the HTML of each of the pages. See the comments for changes and additions to the code. - -```js title=crawler.js -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; - -const WEBSITE_URL = 'https://warehouse-theme-metal.myshopify.com'; -const storeUrl = `${WEBSITE_URL}/collections/sales`; - -const response = await gotScraping(storeUrl); -const html = response.body; - -const $ = cheerio.load(html); - -const productLinks = $('a.product-item__title'); - -// Prepare an empty array for our product URLs. -const productUrls = []; - -for (const link of productLinks) { - const relativeUrl = $(link).attr('href'); - const absoluteUrl = new URL(relativeUrl, WEBSITE_URL); - - // Collect absolute product URLs. - productUrls.push(absoluteUrl); -} - -// Loop over the stored URLs to process -// each product page individually. -for (const url of productUrls) { - // Download HTML. - const productResponse = await gotScraping(url); - const productHtml = productResponse.body; - - // Load into Cheerio to parse the HTML. - const $productPage = cheerio.load(productHtml); - - // Extract the product's title from the

tag. - const productPageTitle = $productPage('h1').text().trim(); - - // Print the title to the terminal to see - // confirm we downloaded the correct pages. - console.log(productPageTitle); -} -``` - -If you run the crawler from your terminal, it will print the titles of all the products on sale in the Warehouse store. - -## Handling errors {#handling-errors} - -The code above is correct, but it's not robust. If something goes wrong, it will crash. That something could be a network error, an internet connection error, or the websites you're trying to reach could be experiencing problems at that moment. Hitting any error like that would cause the current crawler to stop entirely, which means we would lose all the data it had collected so far. - -In programming, you handle errors by catching and handling them. Typically by printing information that the error occurred and/or retrying. - -> The scraping library we'll [show you in the following lessons](./pro_scraping.md) handles errors and retries automatically for you. - -```js title=crawler.js -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; - -const WEBSITE_URL = 'https://warehouse-theme-metal.myshopify.com'; -const storeUrl = `${WEBSITE_URL}/collections/sales`; - -const response = await gotScraping(storeUrl); -const html = response.body; - -const $ = cheerio.load(html); -const productLinks = $('a.product-item__title'); - -const productUrls = []; -for (const link of productLinks) { - const relativeUrl = $(link).attr('href'); - const absoluteUrl = new URL(relativeUrl, WEBSITE_URL); - productUrls.push(absoluteUrl); -} - -for (const url of productUrls) { - // Everything else is exactly the same. - // We only wrapped the code in try/catch blocks. - // The try block passes all errors into the catch block. - // So, instead of crashing the crawler, they can be handled. - try { - // The try block attempts to execute our code - const productResponse = await gotScraping(url); - const productHtml = productResponse.body; - const $productPage = cheerio.load(productHtml); - const productPageTitle = $productPage('h1').text().trim(); - console.log(productPageTitle); - } catch (error) { - // In the catch block, we handle errors. - // This time, we will print - // the error message and the url. - console.error(error.message, url); - } -} -``` - -At the time of writing, none of the links have failed; however, as you crawl more pages, you will surely hit a few errors ๐Ÿ˜‰. The important thing is that the crawler will no longer crash if an error does in fact occur, and that it will be able to download the HTML from the working product links. - -> If you thought that the crawl was taking too long to complete, the [scraping library](./pro_scraping.md) we keep referring to will help once again. It automatically parallelizes the downloads and processing of HTML, which leads to significant speed improvements. - -## Next up {#next} - -In the [next lesson](./scraping_the_data.md), we will complete the scraper by extracting data about all the products from their individual pages. diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/headless_browser.md b/sources/academy/webscraping/scraping_basics_legacy/crawling/headless_browser.md deleted file mode 100644 index 547af850a7..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/crawling/headless_browser.md +++ /dev/null @@ -1,207 +0,0 @@ ---- -title: Headless browsers -description: Learn how to scrape the web with a headless browser using only a few lines of code. Chrome, Firefox, Safari, Edge - all are supported. -sidebar_position: 8 -slug: /scraping-basics-javascript/legacy/crawling/headless-browser -pagination: true -noindex: true ---- - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Learn how to scrape the web with a headless browser using only a few lines of code. Chrome, Firefox, Safari, Edge - all are supported.** - - - ---- - -A headless browser is a browser that runs without a user interface (UI). This means that it's normally controlled by automated scripts. Headless browsers are very popular in scraping because they can help you render JavaScript or programmatically behave like a human user to prevent blocking. The two most popular libraries for controlling headless browsers are [Puppeteer](https://pptr.dev/) and [Playwright](https://playwright.dev/). **Crawlee** supports both. - -## Building a Playwright scraper {#playwright-scraper} - -> Our focus will be on Playwright, which boasts additional features and better documentation. Notably, it originates from the same team responsible for Puppeteer. - -Crawlee has a built-in support for building Playwright scrapers. Let's reuse code of the Cheerio scraper from the previous lesson. It'll take us just a few changes to turn it into a full headless scraper. - -First, we must install Playwright into our project. It's not included in Crawlee, because it's quite large as it bundles all the browsers. - -```shell -npm install playwright -``` - -After Playwright installs, we can proceed with updating the scraper code. Let's create a new file called `browser.js` and put the new code there. As always, the comments in the example describe changes in the code. Everything else is the same as before. - -```js title=browser.js -// First, import PlaywrightCrawler instead of CheerioCrawler -import { PlaywrightCrawler, Dataset } from 'crawlee'; - -const crawler = new PlaywrightCrawler({ - // Second, tell the browser to run with visible UI, - // so that we can see what's going on. - headless: false, - // Third, replace $ with parseWithCheerio function. - requestHandler: async ({ parseWithCheerio, request, enqueueLinks }) => { - console.log(`Fetching URL: ${request.url}`); - - if (request.label === 'start-url') { - await enqueueLinks({ - selector: 'a.product-item__title', - }); - return; - } - - // Fourth, parse the browser's page with Cheerio. - const $ = await parseWithCheerio(); - - const title = $('h1').text().trim(); - const vendor = $('a.product-meta__vendor').text().trim(); - const price = $('span.price').contents()[2].nodeValue; - const reviewCount = parseInt($('span.rating__caption').text(), 10); - const description = $('div[class*="description"] div.rte').text().trim(); - - await Dataset.pushData({ - title, - vendor, - price, - reviewCount, - description, - }); - }, -}); - -await crawler.addRequests([{ - url: 'https://warehouse-theme-metal.myshopify.com/collections/sales', - label: 'start-url', -}]); - -await crawler.run(); -``` - -:::tip Use parseWithCheerio everywhere - -The `parseWithCheerio` function is available even in `CheerioCrawler` and all the other Crawlee crawlers. If you think you'll often switch up the crawlers, you can use it to further reduce the number of needed line changes. - -::: - - -When you run the code with `node browser.js`, you'll see a browser window open and then the individual pages getting scraped, each in a new browser tab. - -That's it. In 4 lines of code, we transformed our crawler from a static HTTP crawler to a headless browser crawler. The crawler now runs the same as before, but uses a Chromium browser instead of plain HTTP requests. This isn't possible without Crawlee. - -Using Playwright in combination with Cheerio like this is only one of many ways how you can utilize Playwright (and Puppeteer) with Crawlee. In the advanced courses of the Academy, we will go deeper into using headless browsers for scraping and web automation (RPA) use cases. - -## Running in headless mode {#running-headless} - -We said that headless browsers didn't have a UI, but while scraping with the above scraper code, you could definitely see the browser. That's because we added the `headless: false` option. This is useful for debugging and seeing what's going on in the browser. Once your scraper is complete, you can remove the line and the crawler will run without a UI. - -You can also switch between headless and headful (with UI) using the [`CRAWLEE_HEADLESS`](https://crawlee.dev/docs/guides/configuration#crawlee_headless) environment variable. This allows you to change the mode without touching your code. - - - - -```shell -CRAWLEE_HEADLESS=1 node browser.js -``` - - - - -```shell -set CRAWLEE_HEADLESS=1 && node browser.js -``` - - - - -```shell -$env:CRAWLEE_HEADLESS=1; & node browser.js -``` - - - - -## Dynamically loaded data {#dynamic-data} - -One of the important benefits of using a browser is that it allows you to extract data that's dynamically loaded, such as data that's only fetched after a user scrolls or interacts with the page. In our case, it's the "**You may also like**" section of the product detail pages. Those products aren't available in the initial HTML, but the browser loads them later using an API. - -![headless-dynamic-data.png](./images/headless-dynamic-data.png) - -:::tip Learn more about dynamic pages - -We discuss dynamic data at length in the [How to scrape dynamic pages](../../../tutorials/node_js/dealing_with_dynamic_pages.md) tutorial, and we also have a special lesson dedicated to it in our [Puppeteer & Playwright course](../../puppeteer_playwright/page/waiting.md). - -::: - -If we added an appropriate selector to our original `CheerioCrawler` code, it would not extract the information, but a browser automatically fetches and renders this extra data. - -Let's add this new extractor to our code. It collects the names of the recommended products. - -```js title=browser.js -// ... -const recommendedProducts = $('.product-recommendations a.product-item__title') - .map((i, el) => $(el).text().trim()) - .toArray(); -// ... -await Dataset.pushData({ - // ... - recommendedProducts, -}); -``` - -And here's the complete, runnable code: - -```js title=browser.js -import { PlaywrightCrawler, Dataset } from 'crawlee'; - -const crawler = new PlaywrightCrawler({ - // We removed the headless: false option to hide the browser windows. - requestHandler: async ({ parseWithCheerio, request, enqueueLinks }) => { - console.log(`Fetching URL: ${request.url}`); - - if (request.label === 'start-url') { - await enqueueLinks({ - selector: 'a.product-item__title', - }); - return; - } - - // Fourth, parse the browser's page with Cheerio. - const $ = await parseWithCheerio(); - - const title = $('h1').text().trim(); - const vendor = $('a.product-meta__vendor').text().trim(); - const price = $('span.price').contents()[2].nodeValue; - const reviewCount = parseInt($('span.rating__caption').text(), 10); - const description = $('div[class*="description"] div.rte').text().trim(); - // We added one more extractor to get all the recommended products. - const recommendedProducts = $('.product-recommendations a.product-item__title') - .map((i, el) => $(el).text().trim()) - .toArray(); - - await Dataset.pushData({ - title, - vendor, - price, - reviewCount, - description, - // And we saved the extracted product names. - recommendedProducts, - }); - }, -}); - -await crawler.addRequests([{ - url: 'https://warehouse-theme-metal.myshopify.com/collections/sales', - label: 'start-url', -}]); - -await crawler.run(); -``` - -When you run the code, you'll find the recommended product names correctly extracted in the dataset files. If you tried the same with our earlier `CheerioCrawler` code, you would find the `recommendedProducts` array empty in your results. That's because Cheerio can't make the API call to retrieve the additional data, like a browser can. - -## Next up {#next} - -We learned how to scrape with Cheerio and Playwright, but how do we export the data for further processing? Let's learn that in the [next and final lesson](./exporting_data.md) of the Basics of crawling section. diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/images/filtering-product-detail-link.png b/sources/academy/webscraping/scraping_basics_legacy/crawling/images/filtering-product-detail-link.png deleted file mode 100644 index dcf001d386..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/crawling/images/filtering-product-detail-link.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/images/filtering-product-urls.png b/sources/academy/webscraping/scraping_basics_legacy/crawling/images/filtering-product-urls.png deleted file mode 100644 index 2a83717c37..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/crawling/images/filtering-product-urls.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/images/filtering-regex-urls.png b/sources/academy/webscraping/scraping_basics_legacy/crawling/images/filtering-regex-urls.png deleted file mode 100644 index f3b41d1344..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/crawling/images/filtering-regex-urls.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/images/headless-dynamic-data.png b/sources/academy/webscraping/scraping_basics_legacy/crawling/images/headless-dynamic-data.png deleted file mode 100644 index 366a7cc31d..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/crawling/images/headless-dynamic-data.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/images/scraping-title.png b/sources/academy/webscraping/scraping_basics_legacy/crawling/images/scraping-title.png deleted file mode 100644 index d4dea251b2..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/crawling/images/scraping-title.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/images/warehouse-links.png b/sources/academy/webscraping/scraping_basics_legacy/crawling/images/warehouse-links.png deleted file mode 100644 index 196cf23d38..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/crawling/images/warehouse-links.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/images/warehouse-store.png b/sources/academy/webscraping/scraping_basics_legacy/crawling/images/warehouse-store.png deleted file mode 100644 index 9442388cef..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/crawling/images/warehouse-store.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/index.md b/sources/academy/webscraping/scraping_basics_legacy/crawling/index.md deleted file mode 100644 index 4479256854..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/crawling/index.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -title: Basics of crawling -description: Learn how to crawl the web with your scraper. How to extract links and URLs from web pages and how to manage the collected links to visit new pages. -sidebar_position: 1.3 -category: courses -slug: /scraping-basics-javascript/legacy/crawling -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Learn how to crawl the web with your scraper. How to extract links and URLs from web pages and how to manage the collected links to visit new pages.** - - - ---- - -Welcome to the second section of our **Web scraping basics for JavaScript devs** course. In the [Basics of data extraction](../data_extraction/index.md) section, we learned how to extract data from a web page. Specifically, a template Shopify site called [Warehouse store](https://warehouse-theme-metal.myshopify.com/). - -![on-sale category of Warehouse store](./images/warehouse-store.png) - -In this section, we will take a look at moving between web pages, which we call **crawling**. We will extract data about all the on-sale products on [Warehouse store](https://warehouse-theme-metal.myshopify.com/collections/sales). To do that, we will need to crawl the individual product pages. - -## How do you crawl? {#how-to-crawl} - -Crawling websites is a fairly straightforward process. We'll start by opening the first web page and extracting all the links (URLs) that lead to the other pages we want to visit. To do that, we'll use the skills learned in the [Basics of data extraction](../data_extraction/index.md) course. We'll add some extra filtering to make sure we only get the correct URLs. Then, we'll save those URLs, so in case our scraper crashes with an error, we won't have to extract them again. And, finally, we will visit those URLs one by one. - -At any point, we can extract URLs, data, or both. Crawling can be separate from data extraction, but it's not a requirement and, in most projects, it's actually easier and faster to do both at the same time. To summarize, it goes like this: - -1. Visit the start URL. -2. Extract new URLs (and data) and save them. -3. Visit one of the new-found URLs and save data and/or more URLs from them. -4. Repeat 2 and 3 until you have everything you need. - -## Next up {#next} - -First, let's make sure we all understand the foundations. In the [next lesson](./recap_extraction_basics.md) we will review the scraper code we already have from the [Basics of data extraction](../data_extraction/index.md) section of the course. diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/pro_scraping.md b/sources/academy/webscraping/scraping_basics_legacy/crawling/pro_scraping.md deleted file mode 100644 index 212a48df94..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/crawling/pro_scraping.md +++ /dev/null @@ -1,248 +0,0 @@ ---- -title: Professional scraping -description: Learn how to build scrapers quicker and get better and more robust results by using Crawlee, an open-source library for scraping in Node.js. -sidebar_position: 7 -slug: /scraping-basics-javascript/legacy/crawling/pro-scraping -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Learn how to build scrapers quicker and get better and more robust results by using Crawlee, an open-source library for scraping in Node.js.** - - - ---- - -While it's definitely an interesting exercise to do all the programming manually, and we hope you enjoyed it, it's neither the most effective, nor the most efficient way of scraping websites. Because we scrape for a living at Apify, we've built a library that we use to scrape tens of millions of pages every day. - -It's called [**Crawlee**](https://crawlee.dev/), and it is, and **always will be**, completely **open-source** and **free** to use. You don't need to sign up for an Apify account or use the Apify platform. You can use it on your personal computer, on any server, or in any cloud environment you want. - -We mentioned the benefits of developing using a dedicated scraping library in the previous lessons, but to recap: - -1. **Faster development time** because you don't have to write boilerplate code. -2. **Fewer bugs**. Crawlee is fully unit-tested and battle-tested on millions of scraper runs. -3. **Faster and cheaper scrapers** because Crawlee automatically scales based on system resources, and we optimize its performance regularly. -4. **More robust scrapers**. Annoying details like retries, proxy management, error handling, and result storage are all handled out-of-the-box by Crawlee. -5. **Helpful community**. You can [join our Discord](https://discord.gg/qkMS6pU4cF) or talk to us [on GitHub](https://github.com/apify/crawlee/discussions). We're almost always there to talk about scraping and programming in general. - -:::tip Crawlee in practice - -If you're still not convinced, [read this story](https://apify.com/success-stories/daltix-analytics-scrapy-python-to-apify) about how a data analytics company saved 90% of scraping costs by switching from Scrapy (a scraping library for Python) to Crawlee. We were pretty surprised ourselves, to be honest. - -::: - -Crawlee factors away and manages the dull and repetitive parts of web scraper development under the hood, such as: - -- Auto-scaling -- Request concurrency -- Queueing requests -- Data storage -- Using and rotating [proxies](../../anti_scraping/mitigation/proxies.md) -- Puppeteer/Playwright setup overhead -- [See all the features](https://crawlee.dev/docs/introduction) - -Crawlee and its resources can be found in various different places: - -1. [Official Crawlee documentation](https://crawlee.dev/) -2. [Crawlee GitHub repository (source code, issues)](https://github.com/apify/crawlee) -3. [Crawlee on npm](https://www.npmjs.com/package/crawlee) - -## Install Crawlee {#crawlee-installation} - -To use Crawlee, we have to install it from npm. Let's add it to our project from the previous lessons by executing this command in your project's folder. - -```shell -npm install crawlee -``` - -After the installation completes, create a new file called `crawlee.js` and add the following code to it: - -```js title=crawlee.js -import { CheerioCrawler } from 'crawlee'; - -console.log('Crawlee works!'); -``` - -We are using the new ESM `import` syntax here (see [Node.js docs](https://nodejs.org/dist/latest-v16.x/docs/api/esm.html#enabling)). To be able to use it, we need to turn our project to `module` in the `package.json` file: - -```json title=package.json -{ - "name": "my-scraping-project", - // highlight-next-line - "type": "module", - "dependencies": { - "crawlee": "^3.0.0" - } -} -``` - -Then, run the code using `node` as usual: - -```shell -node crawlee.js -``` - -You'll see "**Crawlee works!**" printed to the console. If it doesn't work, it means Crawlee didn't install correctly. If that's the case, try deleting the `node_modules` directory and `package-lock.json` file in your project and install Crawlee again. - -> You don't need to `import` any other libraries like Cheerio or Got-Scraping. That's because they're both included in Crawlee's [`CheerioCrawler`](https://crawlee.dev/docs/guides/cheerio-crawler-guide). - -## Prepare the scraper {#coding-the-scraper} - - `CheerioCrawler` automatically visits URLs, downloads HTML using **Got-Scraping**, and parses it with **Cheerio**. The benefit of this over writing the code yourself is that it automatically handles the URL queue, errors, retries, proxies, parallelizes the downloads, and much more. Overall, it removes the need to write a lot of boilerplate code. - -To create a crawler with Crawlee, you only need to provide it with a request handler - a function that gets executed for each page it visits. - -```js title=crawlee.js -import { CheerioCrawler } from 'crawlee'; - -const crawler = new CheerioCrawler({ - // This function will run on every page. - // Among other things, it gives you access - // to parsed HTML with the Cheerio $ function. - requestHandler: async ({ $, request }) => { - console.log('URL:', request.url); - // Print the heading of each visited page. - console.log('Title:', $('h1').text().trim()); - }, -}); -``` - -But the above code still doesn't crawl anything. We need to provide it with URLs to crawl. To do that, we call the crawler's `addRequests` function. - -```js title=crawlee.js -import { CheerioCrawler } from 'crawlee'; - -const crawler = new CheerioCrawler({ - requestHandler: async ({ $, request }) => { - console.log('URL:', request.url); - console.log('Title:', $('h1').text().trim()); - }, -}); - -// Add the Sales category of Warehouse store to the queue of URLs. -await crawler.addRequests([ - 'https://warehouse-theme-metal.myshopify.com/collections/sales', -]); - -await crawler.run(); -``` - -When you run the above code, you'll see some internal Crawlee logs and then the two messages your code printed: - -```text -URL: https://warehouse-theme-metal.myshopify.com/collections/sales -Title: Sales - -``` - -> `crawler.addRequests` uses the [`RequestQueue`](https://crawlee.dev/docs/guides/request-storage#request-queue) under the hood. It's a persistent storage, which means that if your crawler crashes, it doesn't have to start over, but it can continue from where it left off. - -### Summary - -1. We added the first URL to the crawler using the `addRequests` function. -2. `CheerioCrawler` will automatically take the URL from the queue, download its HTML using Got Scraping, and parse it using Cheerio. -3. The crawler executes the [`requestHandler`](https://crawlee.dev/api/cheerio-crawler/interface/CheerioCrawlerOptions#requestHandler), where we extract the page's data using the [`$`](https://crawlee.dev/api/cheerio-crawler/interface/CheerioCrawlingContext) variable. You can also access the request itself using the [`request`](https://crawlee.dev/api/cheerio-crawler/interface/CheerioCrawlingContext#request) variable. - -## Crawling links {#crawling-links} - -The current scraper only visits the Sales category page, but we want detailed data for all the products. We can use the [`enqueueLinks()`](https://crawlee.dev/api/cheerio-crawler/interface/CheerioCrawlingContext#enqueueLinks) function to add more URLs to the queue. The function automatically extracts URLs from the current page based on a provided CSS selector and adds them to the queue. Once added, the crawler will automatically crawl them. - -```js title=crawlee.js -import { CheerioCrawler } from 'crawlee'; - -const crawler = new CheerioCrawler({ - requestHandler: async ({ $, request, enqueueLinks }) => { - console.log('URL:', request.url); - console.log('Title:', $('h1').text().trim()); - - // We only want to enqueue the URLs from the start URL. - if (request.label === 'start-url') { - // enqueueLinks will add all the links - // that match the provided selector. - await enqueueLinks({ - // The selector comes from our earlier code. - selector: 'a.product-item__title', - }); - } - }, -}); - -// Instead of using a string with URL, we're now -// using a request object to add more options. -await crawler.addRequests([{ - url: 'https://warehouse-theme-metal.myshopify.com/collections/sales', - // We label the Request to identify - // it later in the requestHandler. - label: 'start-url', -}]); - -await crawler.run(); -``` - -When you run the code, you'll see the names and URLs of all the products printed to the console. You'll also see that it crawls faster than the manually written code. This is thanks to the parallelization of the requests. - -> If the crawler gets stuck for you at the end, it's ok. It's not actually stuck, but waiting to retry any pages that may have failed. - -## Extracting data {#extracting-data} - -We have the crawler in place, and it's time to extract data. We already have the extraction code from the previous lesson, so we can copy and paste it into the `requestHandler` with tiny changes. Instead of printing results to the terminal, we will save it to disk. - -```js title=crawlee.js -// To save data to disk, we need to import Dataset. -import { CheerioCrawler, Dataset } from 'crawlee'; - -const crawler = new CheerioCrawler({ - requestHandler: async ({ $, request, enqueueLinks }) => { - console.log(`Fetching URL: ${request.url}`); - - if (request.label === 'start-url') { - await enqueueLinks({ - selector: 'a.product-item__title', - }); - // When on the start URL, we don't want to - // extract any data after we extract the links. - return; - } - - // We copied and pasted the extraction code - // from the previous lesson with small - // refactoring: e.g. `$productPage` to `$`. - const title = $('h1').text().trim(); - const vendor = $('a.product-meta__vendor').text().trim(); - const price = $('span.price').contents()[2].nodeValue; - const reviewCount = parseInt($('span.rating__caption').text(), 10); - const description = $('div[class*="description"] div.rte').text().trim(); - - // Instead of printing the results to - // console, we save everything to a file. - await Dataset.pushData({ - title, - vendor, - price, - reviewCount, - description, - }); - }, -}); - -await crawler.addRequests([{ - url: 'https://warehouse-theme-metal.myshopify.com/collections/sales', - label: 'start-url', -}]); - -await crawler.run(); -``` - -When you run the code as usual, you'll see the product URLs printed to the terminal and you'll find the scraped data saved to your disk. Thanks to using the [`Dataset.pushData()`](https://crawlee.dev/docs/introduction/saving-data#whats-datasetpushdata) function, Crawlee automatically created a `storage` directory in your project's location and saved the results there. Each product has its data stored as a separate JSON file. - -```text -./storage/datasets/default/*.json -``` - -Thanks to **Crawlee**, we were able to create a **faster and more robust scraper**, but **with less code** than what was needed for the scraper in the earlier lessons. - -## Next up {#next} - -In the [next lesson](./headless_browser.md) we'll show you how to turn this plain HTTP crawler into a **headless browser** scraper in only a few lines of code. diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/recap_extraction_basics.md b/sources/academy/webscraping/scraping_basics_legacy/crawling/recap_extraction_basics.md deleted file mode 100644 index f5b592b985..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/crawling/recap_extraction_basics.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Recap of data extraction basics -description: Review our e-commerce website scraper and refresh our memory about its code and the programming techniques we used to extract and save the data. -sidebar_position: 1 -slug: /scraping-basics-javascript/legacy/crawling/recap-extraction-basics -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Review our e-commerce website scraper and refresh our memory about its code and the programming techniques we used to extract and save the data.** - - - ---- - -We finished off the [first section](../data_extraction/index.md) of the _Web scraping basics for JavaScript devs_ course by creating a web scraper in Node.js. The scraper collected all the on-sale products from [Warehouse store](https://warehouse-theme-metal.myshopify.com/collections/sales). Let's see the code with some comments added. - -```js -// First, we imported all the libraries we needed to -// download, extract, and convert the data we wanted -import { writeFileSync } from 'fs'; -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; -import { parse } from 'json2csv'; - -// Here, we fetched the website's HTML and saved it to a new variable. -const storeUrl = 'https://warehouse-theme-metal.myshopify.com/collections/sales'; -const response = await gotScraping(storeUrl); -const html = response.body; - -// We used Cheerio, a popular library, to parse (process) -// the downloaded HTML so that we could manipulate it. -const $ = cheerio.load(html); - -// Using the .product-item CSS selector, we collected all the HTML -// elements which contained data about individual products. -const products = $('.product-item'); - -// Then, we prepared a new array to store the results. -const results = []; - -// And looped over all the elements to extract -// information about the individual products. -for (const product of products) { - // The product's title was in an element - // with the CSS class: product-item__title - const titleElement = $(product).find('a.product-item__title'); - const title = titleElement.text().trim(); - // The product's price was in a element - // with the CSS class: price - const priceElement = $(product).find('span.price'); - // Because the also included some useless data, - // we had to extract the price from a specific HTML node. - const price = priceElement.contents()[2].nodeValue.trim(); - - // We added the data to the results array - // in the form of an object with keys and values. - results.push({ title, price }); -} - -// Finally, we formatted the results -// as a CSV file instead of a JS object -const csv = parse(results); - -// Then, we saved the CSV to the disk -writeFileSync('products.csv', csv); -``` - -:::tip Review the basics - -If some of the code is hard for you to understand, please review the [Basics of data extraction](../data_extraction/index.md) section. We will not go through the details again in this section about crawling. - -::: - -:::caution Modern JavaScript features - -We are using JavaScript features like `import` statements and top-level `await`. If you see errors like _Cannot use import outside of a module_, please review the [Project setup lesson](../data_extraction/project_setup.md#modern-javascript), where we explain how to enable those features. - -::: - -## Next up {#next} - -The [next lesson](./finding_links.md) is all about finding links to crawl on the [Warehouse store](https://warehouse-theme-metal.myshopify.com/collections/sales). diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/relative_urls.md b/sources/academy/webscraping/scraping_basics_legacy/crawling/relative_urls.md deleted file mode 100644 index 9c6d18b712..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/crawling/relative_urls.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Relative URLs -description: Learn about absolute and relative URLs used on web pages and how to work with them when parsing HTML with Cheerio in your scraper. -sidebar_position: 4 -slug: /scraping-basics-javascript/legacy/crawling/relative-urls -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Learn about absolute and relative URLs used on web pages and how to work with them when parsing HTML with Cheerio in your scraper.** - - - ---- - -You might have noticed in the previous lesson that while printing URLs to the DevTools console, they would always show in full length, like this: - -```text -https://warehouse-theme-metal.myshopify.com/products/denon-ah-c720-in-ear-headphones -``` - -But in the Elements tab, when checking the `` attributes, the URLs would look like this: - -```text -/products/denon-ah-c720-in-ear-headphones -``` - -What's up with that? This short version of the URL is called a **relative URL**, and the full length one is called an **absolute URL**. - -> [Learn more about absolute and relative URLs](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Web_mechanics/What_is_a_URL#absolute_urls_vs._relative_urls). - -We'll see why the difference between relative URLs and absolute URLs is important a bit later in this lesson. - -## Browser vs Node.js: The Differences {#browser-vs-node} - -Let's update the Node.js code from the [Finding links lesson](./finding_links.md) to see why links with relative URLs can be a problem. - -```js title=crawler.js -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; - -const storeUrl = 'https://warehouse-theme-metal.myshopify.com/collections/sales'; - -const response = await gotScraping(storeUrl); -const html = response.body; - -const $ = cheerio.load(html); - -const productLinks = $('a.product-item__title'); - -for (const link of productLinks) { - const url = $(link).attr('href'); - console.log(url); -} -``` - -When you run this file in your terminal, you'll immediately see the difference. Unlike in the browser, where looping over elements produced absolute URLs, here in Node.js it only produces the relative ones. This is bad, because we can't use the relative URLs to crawl. They don't include all the necessary information. - -## Resolving URLs {#resolving-urls} - -Luckily, there's a process called resolving URLs that creates absolute URLs from relative ones. We need two things. The relative URL, such as `/products/denon-ah-c720-in-ear-headphones`, and the URL of the website where we found the relative URL (which is `https://warehouse-theme-metal.myshopify.com` in our case). - -```js -const websiteUrl = 'https://warehouse-theme-metal.myshopify.com'; -const relativeUrl = '/products/denon-ah-c720-in-ear-headphones'; - -const absoluteUrl = new URL(relativeUrl, websiteUrl); -console.log(absoluteUrl.href); -``` - -In Node.js, when you create a `new URL()`, you can optionally pass a second argument, the base URL. When you do, the URL in the first argument will be resolved using the URL in the second argument. Note that the URL created from `new URL()` is an object, not a string. To get the URL in a string format, we use the `url.href` property, or alternatively the `url.toString()` function. - -When we plug this into our crawler code, we will get the correct - absolute - URLs. - -```js title=crawler.js -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; - -// Split the base URL from the category to use it later. -const WEBSITE_URL = 'https://warehouse-theme-metal.myshopify.com'; -const storeUrl = `${WEBSITE_URL}/collections/sales`; - -const response = await gotScraping(storeUrl); -const html = response.body; - -const $ = cheerio.load(html); - -const productLinks = $('a.product-item__title'); - -for (const link of productLinks) { - const relativeUrl = $(link).attr('href'); - // Resolve relative URLs using the website's URL - const absoluteUrl = new URL(relativeUrl, WEBSITE_URL); - console.log(absoluteUrl.href); -} -``` - -Cheerio can't resolve the URL itself, because until you provide the necessary information - it doesn't know where you originally downloaded the HTML from. The browser always knows which page you're on, so it will resolve the URLs automatically. - -## Next up {#next} - -The [next lesson](./first_crawl.md) will teach you how to use the collected URLs to crawl all the individual product pages. diff --git a/sources/academy/webscraping/scraping_basics_legacy/crawling/scraping_the_data.md b/sources/academy/webscraping/scraping_basics_legacy/crawling/scraping_the_data.md deleted file mode 100644 index f7ecd6476a..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/crawling/scraping_the_data.md +++ /dev/null @@ -1,336 +0,0 @@ ---- -title: Scraping data -description: Learn how to add data extraction logic to your crawler, which will allow you to extract data from all the websites you crawled. -sidebar_position: 6 -slug: /scraping-basics-javascript/legacy/crawling/scraping-the-data -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Learn how to add data extraction logic to your crawler, which will allow you to extract data from all the websites you crawled.** - - - ---- - -At the [very beginning of this course](../index.md), we learned that the term web scraping usually means a combined process of data extraction and crawling. And this is exactly what we'll do in this lesson. We will take the crawling code from the previous lesson, and we will combine it with data extraction code and turn everything into a web scraper. - -## Extracting data from a product detail page {#extracting-data} - -The term product detail page (or PDP) is commonly used on e-commerce websites to describe the page where you can find detailed information about a product. In the Warehouse store, there's, for example, [this page describing Denon headphones](https://warehouse-theme-metal.myshopify.com/products/denon-ah-c720-in-ear-headphones). - -Let's start writing a script that extracts data from this single PDP. We can use this familiar code as a boilerplate. - -```js title=product.js -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; - -const productUrl = 'https://warehouse-theme-metal.myshopify.com/products/denon-ah-c720-in-ear-headphones'; -const response = await gotScraping(productUrl); -const html = response.body; - -const $ = cheerio.load(html); - -// Attribute extraction code will go here. -``` - -We will use the techniques learned in the [Basics of data extraction](../data_extraction/index.md) section to find and extract the following product attributes: - -- title -- vendor -- price -- number of reviews -- description - -![scraping-title.png](./images/scraping-title.png) - -> For brevity, we won't explain how to extract every attribute step-by-step. Review the [Basics of data extraction](../data_extraction/index.md) section to learn about DevTools and extracting data. - -### Title - -Getting the title is quite straightforward. We recommend using `h1` for titles where available, because it's the semantically correct way and therefore unlikely to change. - -```js -const title = $('h1').text().trim(); -``` - -### Vendor - -Vendor name is available as a link with the `product-meta__vendor` class. We're only interested in the text though. - -```js -const vendor = $('a.product-meta__vendor').text().trim(); -``` - -### Price - -We will take a shortcut here and only extract the price as a string that includes currency. In production scrapers, you might want to split it into two fields. - -```js -const price = $('span.price').contents()[2].nodeValue; -``` - -### Number of reviews - -For the review count, we use the `parseInt()` function to get only the number. Otherwise, we would receive a string like **2 reviews** from this element. - -```js -const reviewCount = parseInt($('span.rating__caption').text(), 10); -``` - -### Description - -Getting the description is fairly straightforward as well, but notice the two selectors separated by a space: `div[class*="description"] div.rte`. This is called a [descendant combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator), and it allows you to search for child elements within parent elements. Using any of the selectors separately would lead to unwanted strings in our result. - -```js -const description = $('div[class*="description"] div.rte').text().trim(); -``` - -### Complete extraction code - -This is the final code after putting all the extractors together with the initial boilerplate. It will scrape all the requested attributes from the single URL and print them to the terminal. - -Save it into a new file called `product.js` and run it with `node product.js` to see for yourself. - -```js title=product.js -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; - -const productUrl = 'https://warehouse-theme-metal.myshopify.com/products/denon-ah-c720-in-ear-headphones'; -const response = await gotScraping(productUrl); -const html = response.body; - -const $ = cheerio.load(html); - -const title = $('h1').text().trim(); -const vendor = $('a.product-meta__vendor').text().trim(); -const price = $('span.price').contents()[2].nodeValue; -const reviewCount = parseInt($('span.rating__caption').text(), 10); -const description = $('div[class*="description"] div.rte').text().trim(); - -const product = { - title, - vendor, - price, - reviewCount, - description, -}; - -console.log(product); -``` - -## Crawling product detail pages {#crawling} - -Let's compare the above data extraction example with the crawling code we wrote in the last lesson: - -```js title=crawler.js -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; - -const WEBSITE_URL = 'https://warehouse-theme-metal.myshopify.com'; -const storeUrl = `${WEBSITE_URL}/collections/sales`; - -const response = await gotScraping(storeUrl); -const html = response.body; - -const $ = cheerio.load(html); -const productLinks = $('a.product-item__title'); - -const productUrls = []; -for (const link of productLinks) { - const relativeUrl = $(link).attr('href'); - const absoluteUrl = new URL(relativeUrl, WEBSITE_URL); - productUrls.push(absoluteUrl); -} - -for (const url of productUrls) { - try { - const productResponse = await gotScraping(url); - const productHtml = productResponse.body; - const $productPage = cheerio.load(productHtml); - const productPageTitle = $productPage('h1').text().trim(); - console.log(productPageTitle); - } catch (error) { - console.error(error.message, url); - } -} -``` - -We can see that the code is quite similar. Both scripts download HTML and then process the HTML. To understand how to put them together, we'll go back to the [original process of crawling](./index.md). - -1. Visit the start URL. -2. Extract the next URLs (and data) and save them. -3. Visit one of the collected URLs and save data and/or more URLs. -4. Repeat step 3 until you have everything you need. - -Using this flow as guidance, we should be able to connect the pieces of code together to build a scraper which crawls through the products found in the [Sales category of Warehouse](https://warehouse-theme-metal.myshopify.com/collections/sales), and then scrapes the **title**, **vendor**, **price**, **review count**, and **description** of each of them. - -## Building the final scraper {#building-scraper} - -Let's create a brand-new file called **final.js** and write our scraper code there. We'll show the code step by step for easier orientation. At the end, we'll combine the pieces into a runnable example. - -We'll start by adding our imports and constants at the top of the file, no changes there. - -```js title=final.js -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; - -const WEBSITE_URL = 'https://warehouse-theme-metal.myshopify.com'; -``` - -Then we need to **visit the start URL**. To scrape all the on-sale product links, we need the Sales page as the start URL. - -```js -// ... -const storeUrl = `${WEBSITE_URL}/collections/sales`; - -const response = await gotScraping(storeUrl); -const html = response.body; -``` - -After that, we need to **extract the next URLs** we want to visit (the product detail page URLs). Thus far, the code is exactly the same as the **crawler.js** code. - -```js -// ... -const $ = cheerio.load(html); -const productLinks = $('a.product-item__title'); - -const productUrls = []; -for (const link of productLinks) { - const relativeUrl = $(link).attr('href'); - const absoluteUrl = new URL(relativeUrl, WEBSITE_URL); - productUrls.push(absoluteUrl); -} -``` - -Now the code will start to differ. We will use the crawling logic from earlier to visit all the URLs, but we will replace the placeholder extraction logic we had there. The placeholder logic only extracted the product's title, but we want the vendor, price, number of reviews and description as well. - -```js -// ... - -// A new array to save each product in. -const results = []; - -// An optional array we can save errors to. -const errors = []; - -for (const url of productUrls) { - try { - // Download HTML of each product detail. - const productResponse = await gotScraping(url); - const $productPage = cheerio.load(productResponse.body); - - // Use the data extraction logic from above. - // If copy pasting, be careful about $ -> $productPage. - const title = $productPage('h1').text().trim(); - const vendor = $productPage('a.product-meta__vendor').text().trim(); - const price = $productPage('span.price').contents()[2].nodeValue; - const reviewCount = parseInt($productPage('span.rating__caption').text(), 10); - const description = $productPage('div[class*="description"] div.rte').text().trim(); - - results.push({ - title, - vendor, - price, - reviewCount, - description, - }); - } catch (error) { - // Save information about the error to the - // "errors" array to see what's happened. - errors.push({ url, msg: error.message }); - } -} -``` - -Finally, let's combine the above code blocks into a full runnable example. When you run the below code, it will scrape detailed information about all the products on the first page of the [Warehouse Sales category](https://warehouse-theme-metal.myshopify.com/collections/sales). We added a few console logs throughout the code to see what's going on. - -```js title=final.js -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; - -const WEBSITE_URL = 'https://warehouse-theme-metal.myshopify.com'; -const storeUrl = `${WEBSITE_URL}/collections/sales`; - -console.log('Fetching products on sale.'); -const response = await gotScraping(storeUrl); -const html = response.body; - -const $ = cheerio.load(html); -const productLinks = $('a.product-item__title'); - -const productUrls = []; -for (const link of productLinks) { - const relativeUrl = $(link).attr('href'); - const absoluteUrl = new URL(relativeUrl, WEBSITE_URL); - productUrls.push(absoluteUrl); -} - -console.log(`Found ${productUrls.length} products.`); - -const results = []; -const errors = []; - -for (const url of productUrls) { - try { - console.log(`Fetching URL: ${url}`); - const productResponse = await gotScraping(url); - const $productPage = cheerio.load(productResponse.body); - - const title = $productPage('h1').text().trim(); - const vendor = $productPage('a.product-meta__vendor').text().trim(); - const price = $productPage('span.price').contents()[2].nodeValue; - const reviewCount = parseInt($productPage('span.rating__caption').text(), 10); - const description = $productPage('div[class*="description"] div.rte').text().trim(); - - results.push({ - title, - vendor, - price, - reviewCount, - description, - }); - } catch (error) { - errors.push({ url, msg: error.message }); - } -} - -console.log('RESULTS:', results); -console.log('ERRORS:', errors); -``` - -And here's an example of the results you will see after running the above code. We truncated the descriptions for readability. There should be 24 products in your list. - -```js -[ - { - title: 'JBL Flip 4 Waterproof Portable Bluetooth Speaker', - vendor: 'JBL', - price: '$74.95', - reviewCount: 2, - description: 'JBL Flip 4 is the next generation in the ...', - }, - { - title: 'Sony XBR-950G BRAVIA 4K HDR Ultra HD TV', - vendor: 'Sony', - price: '$1,398.00', - reviewCount: 3, - description: 'Unlock the world of ultimate colors and ...', - }, - { - title: 'Sony SACS9 10" Active Subwoofer', - vendor: 'Sony', - price: '$158.00', - reviewCount: 3, - description: 'Put more punch in your movie ...', - }, -]; -``` - -That's it for the absolute basics of crawling, but we're not done yet. We scraped 24 products from the first page of the Sales category, but the category actually has 50 products on 3 pages. You will learn how to visit all the pages and scrape all the products in the following lessons. - -## Next up {#next} - -In the [next lesson](./pro_scraping.md) we will rewrite the scraper using an open-source web scraping library called [Crawlee](https://crawlee.dev). It will make the scraper more robust while speeding up development at the same time. diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/browser_devtools.md b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/browser_devtools.md deleted file mode 100644 index 9515516fcc..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/browser_devtools.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Starting with browser DevTools -description: Learn about browser DevTools, a valuable tool in the world of web scraping, and how you can use them to extract data from a website. -sidebar_position: 1 -slug: /scraping-basics-javascript/legacy/data-extraction/browser-devtools -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Learn about browser DevTools, a valuable tool in the world of web scraping, and how you can use them to extract data from a website.** - - - ---- - -Even though DevTools stands for developer tools, everyone can use them to inspect a website. Each major browser has its own DevTools. We will use Chrome DevTools as an example, but the advice is applicable to any browser, as the tools are extremely similar. To open Chrome DevTools, you can press **F12** or right-click anywhere in the page and choose **Inspect**. Now go to [Wikipedia](https://www.wikipedia.org/) and open your DevTools there. - -![Wikipedia with Chrome DevTools open](./images/browser-devtools-wikipedia.png) - -## Elements tab {#elements-tab} - -When you first open Chrome DevTools on Wikipedia, you will start on the Elements tab (In Firefox it's called the **Inspector**). You can use this tab to inspect the page's HTML on the left hand side, and its CSS on the right. The items in the HTML view are called **elements**. - -![Elements tab in Chrome DevTools](./images/browser-devtools-elements-tab.png) - -> On a screen that is narrow or has a small resolution, the CSS information can appear under the HTML tab, not on the right. - -Each element is enclosed in an HTML tag. For example `
`, `

`, and `` are all tags. When you add something inside of those tags, like `

Hello!

` you create an element. You can also see elements inside other elements in the **Elements** tab. This is called nesting, and it gives the page its structure. - -At the bottom, there's the **JavaScript console**, which is a powerful tool which can be used to manipulate the website. If the console is not there, you can press **ESC** to toggle it. All of this might look super complicated at first, but don't worry, there's no need to understand everything yet - we'll walk you through all the important things you need to know. - -![Console in Chrome DevTools](./images/browser-devtools-console.png) - -## Selecting an element {#selecting-an-element} - -In the top left corner of DevTools, there's a little arrow icon with a square. - -![Chrome DevTools element selection tool](./images/browser-devtools-element-selection.png) - -Click it and then hover your mouse over **The Free Encyclopedia**, Wikipedia's subtitle. DevTools will show you information about the HTML element being hovered over. Now click the element. It will be selected in the **Elements** tab, which allows for further inspection of the element and its content. - -![Chrome DevTools element hover effect](./images/browser-devtools-hover.png) - -## Interacting with an element {#interacting-with-elements} - -After you select the subtitle element, right-click the highlighted element in the Elements tab to show a menu with available actions. For now, select **Store as global variable** (**Use in Console** in Firefox). You'll see that a new variable called `temp1` (`temp0` in Firefox) appeared in your DevTools Console. You can now use the Console to access the element's properties using JavaScript. - -For example, if you wanted to scrape the text inside the element, you could use the `textContent` property to get it. Copy and paste (or type) the following command into your Console and press Enter. The text of your `temp1` element - The Free Encyclopedia - will display in the Console. - -```js -temp1.textContent; -``` - -Now run this command to get the HTML of the element: - -```js -temp1.outerHTML; -``` - -And finally, run the next command to change the text of the element. - -```js -temp1.textContent = 'Hello World!'; -``` - -By changing HTML elements from the Console, you can change what's displayed on the page. This change only happens on your own computer so don't worry, you haven't hacked Wikipedia. - -![Chrome DevTools JavaScript command execution](./images/browser-devtools-console-commands.png) - -> In JavaScript, the web page is called `document`. From the Console you can interact with it in many ways. Go through [document basics](https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/Using_the_Document_Object_Model) to learn more. - -## Next up {#next} - -In this lesson, we learned the absolute basics of interaction with a page using the DevTools. In the [next lesson](./using_devtools.md), you will learn how to extract data from it. We will extract data about the on-sale products on the [Warehouse store](https://warehouse-theme-metal.myshopify.com). - -It isn't a real store, but a full-featured demo of a Shopify online store. And that is perfect for our purposes. Shopify is one of the largest e-commerce platforms in the world, and it uses all the latest technologies that a real e-commerce web application would use. Learning to scrape a Shopify store is useful, because you can immediately apply the learnings to millions of websites. diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/computer_preparation.md b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/computer_preparation.md deleted file mode 100644 index 90221da22a..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/computer_preparation.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Prepare your computer for programming -description: Set up your computer to be able to code scrapers with Node.js and JavaScript. Download Node.js and npm and run a Hello World script. -sidebar_position: 4 -slug: /scraping-basics-javascript/legacy/data-extraction/computer-preparation -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Set up your computer to be able to code scrapers with Node.js and JavaScript. Download Node.js and npm and run a Hello World script.** - - - ---- - -Before you can start writing scraper code, you need to have your computer set up for it. In this lesson, we will show you all the tools you need to install to successfully write your first scraper. - -## Install Node.js {#install-node} - -Let's start with the installation of Node.js. Node.js is an engine for running JavaScript, quite similar to the browser console we used in the previous lessons. You feed it JavaScript code, and it executes it for you. Why not just use the browser console? Because it's limited in its capabilities. Node.js is way more powerful and is much better suited for coding scrapers. - -If you're on macOS, use [this tutorial to install Node.js](https://blog.apify.com/how-to-install-nodejs/). If you're using Windows [visit the official Node.js website](https://nodejs.org/en/download/). And if you're on Linux, use your package manager to install `nodejs`. - -## Install a text editor {#install-an-editor} - -Many text editors are available for you to choose from when programming. You might already have a preferred one so feel free to use that. Make sure it has syntax highlighting and support for Node.js. If you don't have a text editor, we suggest starting with VSCode. It's free, very popular, and well maintained. [Download it here](https://code.visualstudio.com/download). - -Once you downloaded and installed it, you can open a folder where we will build your scraper. We recommend starting with a new, empty folder. - -![How to open a folder in VSCode](./images/vscode-open-folder.png) - -## Hello world! ๐Ÿ‘‹ {#hello-world} - -Before we start, let's confirm that Node.js was successfully installed on your computer. To do that, run those two commands in your terminal and see if they correctly print your Node.js and npm versions. The next lessons **require Node.js version 16 or higher**. If you skipped Node.js installation and want to use your existing version of Node.js, **make sure that it's 16 or higher**. - -```shell -node -v -npm -v -``` - -If you installed VSCode in the previous paragraph, you can use the integrated terminal. - -![How to open a terminal in VSCode](./images/vscode-open-terminal.png) - -> If you're still wondering what a "terminal" is, we suggest googling for a terminal tutorial for your operating system because individual terminals are different. Sometimes a little, sometimes a lot. - -After confirming that `node` is correctly installed on your computer, use your text editor to create a file called **hello.js** in your folder. - -![How to create a file in VSCode](./images/vscode-create-file.png) - -Now add this piece of code to **hello.js** and save the file. - -```js -console.log('Hello World'); -``` - -Finally, run the below command in your terminal: - -```shell -node hello.js -``` - -You should see **Hello World** printed in your terminal. If you do, congratulations, you are now officially a programmer! ๐Ÿš€ - -![Hello world in VSCode](./images/vscode-hello-world.png) - -## Next up {#next} - -You have your computer set up correctly for development, and you've run your first script. Great! In the [next lesson](./project_setup.md) we'll set up your project to download a website's HTML using Node.js instead of a browser. diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/devtools_continued.md b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/devtools_continued.md deleted file mode 100644 index 329287bb80..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/devtools_continued.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -title: Extracting data with DevTools -description: Continue learning how to extract data from a website using browser DevTools, CSS selectors, and JavaScript via the DevTools console. -sidebar_position: 3 -slug: /scraping-basics-javascript/legacy/data-extraction/devtools-continued -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Continue learning how to extract data from a website using browser DevTools, CSS selectors, and JavaScript via the DevTools console.** - - - ---- - -In the previous parts of the DevTools tutorial, we were able to extract information about a single product from the Sales collection of the [Warehouse store](https://warehouse-theme-metal.myshopify.com/collections/sales). If you missed the previous lessons, please go through them to understand the basic concepts. You don't need any of the code from there, though. We will start from scratch. - -## Find all product elements {#find-all-products} - -First, we will use the `querySelectorAll()` function from the previous lessons to get a list of all the product elements. - -Run this command in your Console: - -```js -const products = document.querySelectorAll('.product-item'); -products.length; -``` - -The `length` property of `products` tells us how many products we have in the list. It says **24** and if you count the number of products on the page, you'll find that it's correct. Good, that means our CSS selector is working perfectly to get all the products. - -![Print all products](./images/devtools-count-products.png) - -## Looping over elements {#looping-over-elements} - -> [Visit this tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration) if you need to refresh the concept of loops in programming. - -Now, we will loop over each product and print their titles. We will use a so-called `for..of` loop to do it. It is a loop that iterates through all items of an array. - -Run the following command in the Console. Some notes: - -- The `a.product-item__title` selector and the extraction code come from the previous lesson. -- The `console.log()` function prints the results to the Console. -- The `trim()` function makes sure there are no useless whitespace characters around our data. - -```js -for (const product of products) { - const titleElement = product.querySelector('a.product-item__title'); - const title = titleElement.textContent.trim(); - console.log(title); -} -``` - -> [Learn more](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) about the `for..of` loop. - -![Print all products' text](./images/devtools-product-titles.png) - -## Extracting more data {#extracting-data-in-loop} - -We will add the price extraction from the previous lesson to the loop. We will also save all the data to an array so that we can work with it. Run this in the Console: - -> The `results.push()` function takes its argument and pushes (adds) it to the `results` array. [Learn more about it here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push). - -```js -const results = []; - -for (const product of products) { - const titleElement = product.querySelector('a.product-item__title'); - const title = titleElement.textContent.trim(); - - const priceElement = product.querySelector('span.price'); - const price = priceElement.childNodes[2].nodeValue.trim(); - - results.push({ title, price }); -} -``` - -After running the code, you'll see **24** printed to the Console. That's because the `results` array includes 24 products. - -Now, run this command in the Console to print all the products: - -```js -console.log(results); -``` - -![Print all products' data](./images/devtools-print-all-products.png) - -> You may notice that some prices include the word **From**, indicating that the price is not final. If you wanted to process this data further, you would want to remove this from the price and instead save this information to another field. - -## Summary - -Let's recap the web scraping process. First, we used DevTools to **find the element** that holds data about a single product. Then, inside this **parent** element we **found child elements** that contained the data (title, price) we were looking for. - -Second, we used the `document.querySelector()` function and its `All` variant to **find the data programmatically**, using their **CSS selectors**. - -And third, we wrapped this data extraction logic in a **loop** to automatically find the data not only for a single product, but for **all the products** on the page. ๐ŸŽ‰ - -## Next up {#next} - -And that's it! With a bit of trial and error, you will be able to extract data from any webpage that's loaded in your browser. This is a useful skill on its own. It will save you time copy-pasting stuff when you need data for a project. - -More importantly though, it taught you the basics to start programming your own scrapers. In the [next lessons](./computer_preparation.md), we will teach you how to create your own web data extraction script using JavaScript and Node.js. diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-console-commands.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-console-commands.png deleted file mode 100644 index e923d2e4f0..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-console-commands.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-console.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-console.png deleted file mode 100644 index b1520bb609..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-console.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-element-selection.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-element-selection.png deleted file mode 100644 index 5835109a7d..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-element-selection.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-elements-tab.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-elements-tab.png deleted file mode 100644 index 63bf784162..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-elements-tab.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-hover.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-hover.png deleted file mode 100644 index 65e4fe5eca..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-hover.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-wikipedia.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-wikipedia.png deleted file mode 100644 index 9486fdc8f9..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/browser-devtools-wikipedia.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/csv-data-in-sheets.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/csv-data-in-sheets.png deleted file mode 100644 index 43d904787a..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/csv-data-in-sheets.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-clean-price.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-clean-price.png deleted file mode 100644 index a8d9715b86..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-clean-price.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-cleaning-noise.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-cleaning-noise.png deleted file mode 100644 index 6fabe3b3ce..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-cleaning-noise.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-class.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-class.png deleted file mode 100644 index 59e6d934d7..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-class.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-product-hover.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-product-hover.png deleted file mode 100644 index a74c836b00..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-product-hover.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-product-name.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-product-name.png deleted file mode 100644 index d9225960ba..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-product-name.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-query-all.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-query-all.png deleted file mode 100644 index ac298e30fe..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-query-all.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-query-hover.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-query-hover.png deleted file mode 100644 index b7ba92aa8c..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-query-hover.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-query.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-query.png deleted file mode 100644 index c0272caad0..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-query.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-warehouse.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-warehouse.png deleted file mode 100644 index d0d72527dd..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-collection-warehouse.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-count-products.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-count-products.png deleted file mode 100644 index 2ce7c7b056..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-count-products.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-extract-product-price.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-extract-product-price.png deleted file mode 100644 index 1ad2fe64ea..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-extract-product-price.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-extract-product-title.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-extract-product-title.png deleted file mode 100644 index 3e7c029490..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-extract-product-title.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-find-child-elements.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-find-child-elements.png deleted file mode 100644 index f1d4e8b26a..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-find-child-elements.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-print-all-products.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-print-all-products.png deleted file mode 100644 index f599f0884d..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-print-all-products.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-print-parent-text.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-print-parent-text.png deleted file mode 100644 index 94df0f3f78..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-print-parent-text.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-product-titles.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-product-titles.png deleted file mode 100644 index 77e022dd90..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-product-titles.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-split-price.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-split-price.png deleted file mode 100644 index 9951fb34a9..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/devtools-split-price.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/node-scraper-title.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/node-scraper-title.png deleted file mode 100644 index 3993c6cc56..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/node-scraper-title.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-create-file.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-create-file.png deleted file mode 100644 index 41a7011bb2..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-create-file.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-hello-world.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-hello-world.png deleted file mode 100644 index 5638bf55b4..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-hello-world.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-npm-init.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-npm-init.png deleted file mode 100644 index f321759e3f..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-npm-init.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-open-folder.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-open-folder.png deleted file mode 100644 index 9b8cd10f2d..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-open-folder.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-open-terminal.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-open-terminal.png deleted file mode 100644 index 7e1f7f4ddd..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-open-terminal.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-test-setup.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-test-setup.png deleted file mode 100644 index 851525a866..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-test-setup.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-type-module.png b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-type-module.png deleted file mode 100644 index 0fe676f9f8..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/images/vscode-type-module.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/index.md b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/index.md deleted file mode 100644 index 3063c0bf02..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/index.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Basics of data extraction -description: Learn about HTML, CSS, and JavaScript, the basic building blocks of a website, and how to use them in web scraping and data extraction. -sidebar_position: 1.2 -category: courses -slug: /scraping-basics-javascript/legacy/data-extraction -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Learn about HTML, CSS, and JavaScript, the basic building blocks of a website, and how to use them in web scraping and data extraction.** - - - ---- - -Every web scraping project starts with some detective work. To a human, it's completely obvious where the data is on the web page, but a computer needs very precise instructions to find the data we want. We can leverage three elementary components of each website to give those instructions: HTML, CSS, and JavaScript - -## HTML {#html} - -For the browser to be able to show you the web page with all its text and images, the data needs to be present somewhere. This data source is called HTML (HyperText Markup Language) and it gets downloaded to your computer whenever you open a website. If you want to extract data from a website, you need to show your computer where to find it in the HTML. - -> To learn more about markup, we recommend the [resources about HTML](https://developer.mozilla.org/en-US/docs/Learn/HTML) provided by MDN, the official documentation of the web. - -## CSS {#css} - -CSS (Cascading Style Sheets) is a language that is used to give websites their style. It controls shapes, colors, positioning and even animations. The style is then added to the page's HTML and together, they define the page's content and structure. In web scraping, we can leverage CSS to find the data we want using CSS selectors. - -> To learn more about styles and selectors, we recommend the [resources about CSS](https://developer.mozilla.org/en-US/docs/Learn/CSS) provided by MDN, the official documentation of the web. - -## JavaScript {#javascript} - -HTML and CSS give websites their structure and style, but they are static. To be able to meaningfully interact with a website, you need to throw JavaScript into the mix. It is the language of the web, and you don't need to be a programmer to learn the basics. You don't even need any special software, because you can try it right now, in your browser. - -> To learn more about programming in browser, we recommend the [resources about JavaScript](https://developer.mozilla.org/en-US/docs/Learn/JavaScript) provided by MDN, the official documentation of the web. - -## Next up {#next} - -We will show you [how to use the browser DevTools](./browser_devtools.md) to inspect and interact with a web page. diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/node_continued.md b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/node_continued.md deleted file mode 100644 index c7f704aa8a..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/node_continued.md +++ /dev/null @@ -1,182 +0,0 @@ ---- -title: Extracting data with Node.js -description: Continue learning how to create a web scraper with Node.js and Cheerio. Learn how to parse HTML and print the results of the data your scraper has collected. -sidebar_position: 7 -slug: /scraping-basics-javascript/legacy/data-extraction/node-continued -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Continue learning how to create a web scraper with Node.js and Cheerio. Learn how to parse HTML and print the results of the data your scraper has collected.** - - - ---- - -In the first part of the Node.js tutorial we downloaded the HTML of our [Warehouse store](https://warehouse-theme-metal.myshopify.com/collections/sales) and parsed it with Cheerio. Now, we will replicate the extraction logic from the [Extracting Data with DevTools](./using_devtools.md) lessons and finish our scraper. - -## Querying data with Cheerio {#querying-with-cheerio} - -As a reminder, the data we need for each product on the page is available in the elements that have the `product-item` class attribute. - -![Selecting an element from the Elements tab](./images/devtools-collection-class.png) - -To get all the elements with that class using Cheerio, we call the `$` function with the appropriate CSS selector. Same as we would with the `document.querySelectorAll()` function. - -```js -// In browser DevTools Console -const products = document.querySelectorAll('.product-item'); -``` - -```js -// In Node.js with Cheerio -const products = $('.product-item'); -``` - -We will use the same approach as in the previous DevTools lessons. Using a `for..of` loop we will iterate over the list of products we saved in the `products` variable. The code is a little different from DevTools, because we're using Node.js and Cheerio instead of a browser's native DOM manipulation functions, but the principle is exactly the same. - -Replace the code in your **main.js** with the following, and run it with `node main.js` in your terminal. - -```js -// main.js -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; - -const storeUrl = 'https://warehouse-theme-metal.myshopify.com/collections/sales'; - -// Download HTML with Got Scraping -const response = await gotScraping(storeUrl); -const html = response.body; - -// Parse HTML with Cheerio -const $ = cheerio.load(html); - -// Find all products on the page -const products = $('.product-item'); - -// Loop through all the products -// and print their text to terminal -for (const product of products) { - const productElement = $(product); - const productText = productElement.text(); - - console.log(productText); -} -``` - -After you run this script, you will see data of all the 24 products printed in your terminal. The output will be messy, but that's ok. Next, we will clean it. - -## Extracting product data {#extracting-data} - -To clean the output, we need to repeat the process from the DevTools lessons and add individual data point extraction to the loop. From those lessons, we know that each of our product cards includes an `
` element which holds the product's title, and a `` element which includes the product's price. - -![Finding child elements in Elements tab](./images/devtools-find-child-elements.png) - -We will loop over all the `products` and extract the data points from each of them using the `for..of` loop. For reference, this a part of the code from the DevTools lesson, where we collected the data using the browser **DevTools Console**: - -```js -// This code will only work in the browser, and NOT in Node.js -const results = []; - -for (const product of products) { - const titleElement = product.querySelector('a.product-item__title'); - const title = titleElement.textContent.trim(); - - const priceElement = subwoofer.querySelector('span.price'); - const price = priceElement.childNodes[2].nodeValue.trim(); - - results.push({ title, price }); -} -``` - -And this snippet shows the same piece of code when using **Node.js and Cheerio**: - -```js -const results = []; - -for (const product of products) { - const titleElement = $(product).find('a.product-item__title'); - const title = titleElement.text().trim(); - - const priceElement = $(product).find('span.price'); - const price = priceElement.contents()[2].nodeValue.trim(); - - results.push({ title, price }); -} -``` - -The main difference is that we used the [`.find()`](https://cheerio.js.org/classes/Cheerio.html#find) function to select the title and price elements and also the `.contents()` function instead of the `childNodes` attribute. If you find the differences confusing, don't worry about it. It will begin to feel very natural after a bit of practice. - -The final scraper code looks like this. Replace the code in your **main.js** file with this code and run it using `node main.js` in your terminal. - -```js -// main.js -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; - -const storeUrl = 'https://warehouse-theme-metal.myshopify.com/collections/sales'; - -// Download HTML with Got Scraping -const response = await gotScraping(storeUrl); -const html = response.body; - -// Parse HTML with Cheerio -const $ = cheerio.load(html); - -// Find all products on the page -const products = $('.product-item'); - -const results = []; -for (const product of products) { - const titleElement = $(product).find('a.product-item__title'); - const title = titleElement.text().trim(); - - const priceElement = $(product).find('span.price'); - const price = priceElement.contents()[2].nodeValue.trim(); - - results.push({ title, price }); -} - -console.log(results); -``` - -After running the code, you will see this output in your terminal: - -```js -[ - { - title: 'JBL Flip 4 Waterproof Portable Bluetooth Speaker', - price: '$74.95', - }, - { - title: 'Sony XBR-950G BRAVIA 4K HDR Ultra HD TV', - price: 'From $1,398.00', - }, - { - title: 'Sony SACS9 10" Active Subwoofer', - price: '$158.00', - }, - { - title: 'Sony PS-HX500 Hi-Res USB Turntable', - price: '$398.00', - }, - { - title: 'Klipsch R-120SW Powerful Detailed Home Speaker - Unit', - price: '$324.00', - }, - // ...and more -]; -``` - -Congratulations! You completed the **Basics of data extraction** section of the Web scraping basics for JavaScript devs course. A quick recap of what you learned: - -1. The basic terminology around web scraping, crawling, HTML, CSS and JavaScript. -2. How to use browser DevTools and Console to inspect web pages and manipulate them using CSS and JavaScript. -3. How to install Node.js and set up your computer for building scrapers. -4. How to download a website's HTML using Got Scraping and then parse it using Cheerio to extract valuable data. - -Great job! ๐Ÿ‘๐ŸŽ‰ - -What's next? While we were able to extract the data, it's not super useful to have it printed to the terminal. In the [next, bonus lesson](./save_to_csv.md), we will learn how to convert the data to a CSV and save it to a file. diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/node_js_scraper.md b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/node_js_scraper.md deleted file mode 100644 index 94e3282c4f..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/node_js_scraper.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Scraping with Node.js -description: Learn how to use JavaScript and Node.js to create a web scraper, plus take advantage of the Cheerio and Got-scraping libraries to make your job easier. -sidebar_position: 6 -slug: /scraping-basics-javascript/legacy/data-extraction/node-js-scraper -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Learn how to use JavaScript and Node.js to create a web scraper, plus take advantage of the Cheerio and Got-scraping libraries to make your job easier.** - - - ---- - -Finally, we have everything ready to start scraping! Yes, the setup was a bit daunting, but luckily, you only have to do it once. We have our project, we have our **main.js** file, so let's add some code to it. - -## Downloading HTML {#downloading-html} - -We will use the `got-scraping` library to download the HTML of products that are [on sale in the Warehouse store](https://warehouse-theme-metal.myshopify.com/collections/sales). We already worked with this page earlier in the [Extracting Data with DevTools](./using_devtools.md) lessons. - -Replace the contents of your **main.js** file with this code: - -```js -// main.js -import { gotScraping } from 'got-scraping'; - -const storeUrl = 'https://warehouse-theme-metal.myshopify.com/collections/sales'; - -const response = await gotScraping(storeUrl); -const html = response.body; -console.log(html); -``` - -Now run the script using the `node main.js` command from the previous lesson. After a brief moment, you should see the page's HTML printed to your terminal. - -> `gotScraping` is an `async` function and the `await` keyword is used to pause execution of the script until it returns the `response`. If you're new to this, go through an [introduction to asynchronous JavaScript](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous). - -## Parsing HTML {#parsing-html} - -Having the HTML printed to the terminal is not very helpful. To extract the data, we first have to parse it. Parsing the HTML allows us to query the individual HTML elements, similarly to the way we did it in the browser in the [Extracting Data with DevTools](./using_devtools.md) lessons. - -To parse the HTML with the `cheerio` library. Replace the code in your **main.js** with the following code: - -```js -// main.js -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; - -const storeUrl = 'https://warehouse-theme-metal.myshopify.com/collections/sales'; - -// Download HTML with Got Scraping -const response = await gotScraping(storeUrl); -const html = response.body; - -// Parse HTML with Cheerio -const $ = cheerio.load(html); -const headingElement = $('h1'); -const headingText = headingElement.text(); - -// Print page title to terminal -console.log(headingText); -``` - -When you run the above script, **Sales** will be printed to the terminal. That's because it's the heading of the Sales page of the Warehouse Store which is located in a `h1` element. - -![Scraping page heading](./images/node-scraper-title.png) - -Great, we successfully parsed the HTML and extracted the text of the `

` element from it using Node.js and Cheerio. Let's break the code down. - -The script first downloaded the page's HTML using the Got Scraping library. Then, it parsed the downloaded `html` with `cheerio` using the `load()` function, and allowed us to work with it using the `$` variable (the `$` name is an old convention). The next `$('h1')` function call looked inside the parsed HTML and found the `

` element. Finally, the script extracted the text from the element using the `.text()` function and printed it to the terminal with `console.log()`. - -> `$('h1')` is very similar to calling `document.querySelector('h1')` in the browser and `element.text()` is similar to `element.textContent` from the earlier DevTools lessons. [Visit the cheerio documentation](https://github.com/cheeriojs/cheerio#readme) to learn more about its syntax. - -## Next up {#next} - -In the [next lesson](./node_continued.md) we will learn more about Cheerio and use it to extract all the products' data from Fakestore. diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/project_setup.md b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/project_setup.md deleted file mode 100644 index 10bca55b74..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/project_setup.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Setting up your project -description: Create a new project with npm and Node.js. Install necessary libraries, and test that everything works before starting the next lesson. -sidebar_position: 5 -slug: /scraping-basics-javascript/legacy/data-extraction/project-setup -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Create a new project with npm and Node.js. Install necessary libraries, and test that everything works before starting the next lesson.** - - - ---- - -When you open a website in a browser, the browser first downloads the page's HTML. To do the same thing with Node.js, we will install a program - an npm module - to help us with it. npm modules are installed using `npm`, which is another program, automatically installed with Node.js. - -> The [npmjs.com](https://www.npmjs.com/) registry offers a huge collection of open-source libraries for Node.js. You can (and you should) utilize it to save time and tap into the amazing open-source community around JavaScript and Node.js. - -## Creating a new project with npm {#creating-a-project} - -Before we can install npm modules, we need to create an npm project. To do that, you can create a new directory or use the one that you already have open in VSCode (you can delete the **hello.js** file now) and from that directory run this command in your terminal: - -```shell -npm init -y -``` - -It will set up an empty npm project for you and create a file called **package.json**. This is a very important file in Node.js programming as it contains information about the project. - -![npm init with VSCode](./images/vscode-npm-init.png) - -### Use modern JavaScript {#modern-javascript} - -Node.js and npm support two types of projects, let's call them legacy and modern. For backwards compatibility, the legacy version is used by default. To switch to the modern version, open your **package.json** and add this line to the end of the JSON object. Don't forget to add a comma to the end of the previous line ๐Ÿ˜‰ - -```text -"type": "module" -``` - -![Update package.json with VSCode](./images/vscode-type-module.png) - -> More recent versions of npm might already have `"type": "commonjs",` pre-defined; if so, simply replace `commonjs` with `module`. - -If you want to learn more about JSON and its syntax, we recommend [this tutorial on MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON). - -## Installing necessary libraries {#install-libraries} - -Now that we have a project set up, we can install npm modules into the project. Let's install libraries that will help us with downloading and processing websites' HTML. In the project directory, run the following command, which will install two libraries into your project. **got-scraping** and Cheerio. - -```shell -npm install got-scraping cheerio -``` - -[**got-scraping**](https://github.com/apify/got-scraping) is a library that's made especially for scraping and downloading page's HTML. It's based on the popular [**got** library](https://github.com/sindresorhus/got), which means any features of **got** are also available in **got-scraping**. Both **got** and **got-scraping** are HTTP clients. To learn more about HTTP, [visit this MDN tutorial](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP). - -[Cheerio](https://github.com/cheeriojs/cheerio) is a popular Node.js library for parsing and processing HTML. If you know how to work with [jQuery](https://jquery.com/), you'll find Cheerio familiar. - -## Test everything {#testing} - -With the libraries installed, create a new file in the project's folder called **main.js**. This is where we will put all our code. Before we start scraping, though, let's do a check that everything was installed correctly. Add this piece of code inside **main.js**. - -```js -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; - -console.log('it works!'); -``` - -Those `import` statements tell Node.js that it should give you access to the **got-scraping** library under the `gotScraping` variable and the Cheerio library under the `cheerio` variable. - -Now run this command in your terminal: - -```shell -node main.js -``` - -If you see **it works!** printed in your terminal, great job! You set up everything correctly. If you see an error that says _Cannot use import statement outside a module_, go back to the [Use modern JavaScript](#modern-javascript) paragraph and add the `type` property to your **package.json**. If you see a different error, try copying and pasting it into Google, and you'll find a solution soon. - -![Test your setup with VSCode](./images/vscode-test-setup.png) - -## Next up {#next} - -With the project set up, the [next lesson](./node_js_scraper.md) will show you how to use **got-scraping** to download the website's HTML and extract data from it with Cheerio. diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/save_to_csv.md b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/save_to_csv.md deleted file mode 100644 index 3066a18b7c..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/save_to_csv.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Saving results to CSV -description: Learn how to save the results of your scraper's collected data to a CSV file that can be opened in Excel, Google Sheets, or any other spreadsheets program. -sidebar_position: 8 -slug: /scraping-basics-javascript/legacy/data-extraction/save-to-csv -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Learn how to save the results of your scraper's collected data to a CSV file that can be opened in Excel, Google Sheets, or any other spreadsheets program.** - - - ---- - -In the last lesson, we were able to extract data about all the on-sale products from [Warehouse Store](https://warehouse-theme-metal.myshopify.com/collections/sales). That's great. But we ended up with results printed to the terminal, which is not very useful for further processing. In this lesson, we'll learn how to save that data into a CSV file that you can then open in Excel or Google Sheets. - -## Converting to CSV {#converting-to-csv} - -It might look like a big programming challenge to transform a JavaScript object into a CSV, but thanks to npm, this is going to be a walk in the park. Google search **json to csv npm**. You will find that there's a library called [`json2csv`](https://www.npmjs.com/package/json2csv) that can convert a JavaScript object to CSV format with a single function call. _Perfect!_ - -To install `json2csv`, run this command in your terminal. You need to be in the project's folder - the folder which has the `package.json` file. - -```shell -npm i json2csv -``` - -First, we need to import the `parse()` function from the library. - -```js -import { parse } from 'json2csv'; -``` - -Next, we need to parse the `results` array from the previous lesson with the imported function. - -```js -const csv = parse(results); -``` - -The full code including the earlier scraping part now looks like this. Replace the contents of your **main.js** file with this code: - -```js -// main.js -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; -import { parse } from 'json2csv'; // <---- added a new import - -const storeUrl = 'https://warehouse-theme-metal.myshopify.com/collections/sales'; - -const response = await gotScraping(storeUrl); -const html = response.body; - -const $ = cheerio.load(html); - -const products = $('.product-item'); - -const results = []; -for (const product of products) { - const titleElement = $(product).find('a.product-item__title'); - const title = titleElement.text().trim(); - - const priceElement = $(product).find('span.price'); - const price = priceElement.contents()[2].nodeValue.trim(); - - results.push({ title, price }); -} - -const csv = parse(results); // <---- added parsing of results to CSV -console.log(csv); -``` - -Now run the script with `node main.js`. The newly created CSV will be printed to the terminal. - -```text -"title","price" -"JBL Flip 4 Waterproof Portable Bluetooth Speaker","$74.95" -"Sony XBR-950G BRAVIA 4K HDR Ultra HD TV","From $1,398.00" -"Sony SACS9 10"" Active Subwoofer","$158.00" -"Sony PS-HX500 Hi-Res USB Turntable","$398.00" -"Klipsch R-120SW Powerful Detailed Home Speaker - Unit","$324.00" -"Denon AH-C720 In-Ear Headphones","$119.00" -"Sony XBR-85X850F 85-Inch 4K Ultra HD Smart LED TV","$3,498.00" -"Sony XBR-75X850F 75-Inch 4K Ultra HD Smart LED TV","$1,998.00" -"Sony XBR-55A8F 55-Inch 4K Ultra HD Smart BRAVIA OLED TV","$2,298.00" -... -``` - -## Writing the CSV to a file {#writing-to-file} - -The final task that remains is to save our CSV formatted data to a file on our disk, so we can open it or send it to someone. For this, we don't need any extra npm packages because functions for saving files are included in Node.js. - -First, we import the `writeFileSync` function from the `fs` (file system) package. - -```js -import { writeFileSync } from 'fs'; -``` - -and then call it with a file name and the CSV data. - -```js -writeFileSync('products.csv', csv); -``` - -When we complete the code, it looks like this. Replace the code in your **main.js** file with this new code. - -```js -// main.js -import { writeFileSync } from 'fs'; // <---- added a new import -import { gotScraping } from 'got-scraping'; -import * as cheerio from 'cheerio'; -import { parse } from 'json2csv'; - -const storeUrl = 'https://warehouse-theme-metal.myshopify.com/collections/sales'; - -const response = await gotScraping(storeUrl); -const html = response.body; - -const $ = cheerio.load(html); - -const products = $('.product-item'); - -const results = []; -for (const product of products) { - const titleElement = $(product).find('a.product-item__title'); - const title = titleElement.text().trim(); - - const priceElement = $(product).find('span.price'); - const price = priceElement.contents()[2].nodeValue.trim(); - - results.push({ title, price }); -} - -const csv = parse(results); -writeFileSync('products.csv', csv); // <---- added writing of CSV to file -``` - -Finally, run it with `node main.js` in your terminal. After running it, you will find the **products.csv** file in your project folder. And when you open it with Excel/Google Sheets - voila! - -![Displaying CSV data in Google Sheets](./images/csv-data-in-sheets.png) - -This marks the end of the **Basics of data extraction** section of Web scraping basics for JavaScript devs. If you enjoyed the course, give us a thumbs up down below and if you're eager to learn more... - -## Next up {#next} - -Next up are the [**Basics of crawling**](../crawling/index.md). You already know how to build a scraper that finds all the products on sale in the [Warehouse Store](https://warehouse-theme-metal.myshopify.com/collections/sales). In the [**Basics of crawling**](../crawling/index.md) section you will learn how to open individual product pages of those products and scrape information that's not available on the listing page, like SKUs, descriptions or reviews. diff --git a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/using_devtools.md b/sources/academy/webscraping/scraping_basics_legacy/data_extraction/using_devtools.md deleted file mode 100644 index ba978c4adc..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/data_extraction/using_devtools.md +++ /dev/null @@ -1,213 +0,0 @@ ---- -title: Finding elements with DevTools -description: Learn how to use browser DevTools, CSS selectors, and JavaScript via the DevTools console to extract data from a website. -sidebar_position: 2 -slug: /scraping-basics-javascript/legacy/data-extraction/using-devtools -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../../scraping_basics/_legacy.mdx'; - -**Learn how to use browser DevTools, CSS selectors, and JavaScript via the DevTools console to extract data from a website.** - - - ---- - -With the knowledge of the basics of DevTools we can finally try doing something more practical - extracting data from a website. Let's try collecting the on-sale products from the [Warehouse store](https://warehouse-theme-metal.myshopify.com/). We will use CSS selectors, JavaScript, and DevTools to achieve this task. - -> **Why use a Shopify demo and not a real e-commerce store like Amazon?** Because real websites are usually bulkier, littered with promotions, and they change very often. Many have multiple versions of pages, and you never know in advance which one you will get. It will be important to learn how to deal with these challenges in the future, but for this beginner course, we want to have a light and stable environment. -> -> Some other courses use so-called scraping playgrounds or sandboxes. Those are websites made solely for the purpose of learning scraping. We find those too dumbed down and not representative of real websites. The Shopify demo is a full-featured, real-world website. - -## Getting structured data from HTML {#getting-structured-data} - -When you open up the [Sales section of Warehouse](https://warehouse-theme-metal.myshopify.com/collections/sales), you'll see that there's a grid of products on the page with names and pictures of products. We will learn how to extract all this information. - -![Warehouse store with DevTools open](./images/devtools-collection-warehouse.png) - -Open DevTools and select the name of the **Sony SACS9 Active Subwoofer**. When you click on it, it will get highlighted in the Elements tab. - -![Selecting an element with DevTools](./images/devtools-collection-product-name.png) - -Great, you have selected the element which contains the name of the subwoofer. Now we want to find all the elements that contain all the information about this subwoofer. Price, number of reviews, image and everything else you might need. We will use the **Elements** tab to do that. You can hover over the elements in the Elements tab, and they will get highlighted on the page as you move the mouse. - -Start from the previously selected element with the subwoofer's name and move your mouse up, hovering over each element, until you find the one that highlights the entire product card. Alternatively, you can press the up arrow a few times to get the same result. - -The element that contains all the information about the subwoofer is called a **parent element**, and all the nested elements, including the subwoofer's name, price and everything else, are **child elements**. - -![Selecting an element with hover](./images/devtools-collection-product-hover.png) - -Now that we know how the parent element looks, we can extract its data, including the data of its children. Notice that the element has a `class` attribute with multiple values like `product-item` or `product-item--vertical`. Let's use those classes in the Console to extract data. - -![Class attribute in DevTools](./images/devtools-collection-class.png) - -## Selecting elements in Console {#selecting-elements} - -We know how to find an element manually using the DevTools, but that's not very useful for automated scraping. We need to tell the computer how to find it as well. We can do that using JavaScript and CSS selectors. The function to do that is called `document.querySelector()` and it will find the first element in the page's HTML matching the provided CSS selector. - -For example `document.querySelector('div')` will find the first `
` element. And `document.querySelector('.my-class')` (notice the period `.`) will find the first element with the class `my-class`, such as `
` or `

`. - -You can also combine selectors. `document.querySelector('p.my-class')` will find all `

` elements, but no `

`. - -Let's try to use `document.querySelector()` to find the **Sony subwoofer**. Earlier we mentioned that the parent element of the subwoofer had, among others, the `product-item` class. We can use the class to look up the element. Copy or type (don't miss the period `.` in `.product-item`) the following function into the Console and press Enter. - -```js -document.querySelector('.product-item'); -``` - -It will produce a result like this, but it **won't be** the Sony subwoofer. - -![Query a selector with JavaScript](./images/devtools-collection-query.png) - -:::note About the missing semicolon - -In the screenshot, there is a missing semicolon `;` at the end of the line. In JavaScript, semicolons are optional, so it makes no difference. - -::: - -When we look more closely by hovering over the result in the Console, we find that instead of the Sony subwoofer, we found a JBL Flip speaker. Why? Because earlier we explained that `document.querySelector('.product-item')` finds the **first element** with the `product-item` class, and the JBL speaker is the first product in the list. - -![Hover over a query result](./images/devtools-collection-query-hover.png) - -We need a different function: `document.querySelectorAll()` (notice the `All` at the end). This function does not find only the first element, but all the elements that match the provided selector. - -Run the following function in the Console: - -```js -document.querySelectorAll('.product-item'); -``` - -It will return a `NodeList` (a type of array) with many results. Expand the results by clicking the small arrow button and then hover over the third (number 2, indexing starts at 0) element in the list. You'll find that it's the Sony subwoofer we're looking for. - -![Hover over a query result](./images/devtools-collection-query-all.png) - -Naturally, this is the method we use mostly in web scraping, because we're usually interested in scraping all the products from a page, not just a single product. - -:::note Elements or nodes? - -The list is called a `NodeList`, because browsers understand a HTML document as a tree of nodes. Most of the nodes are HTML elements, but there can be also text nodes for plain text, and others. - -::: - -## How to choose good selectors {#choose-good-selectors} - -Often you can select the same element with different CSS selectors. Try to choose selectors that are **simple**, **human-readable**, **unique** and **semantically connected** to the data. Selectors that meet these criteria are sometimes called **resilient selectors**, because they're the most reliable and least likely to change with website updates. If you can, avoid randomly generated attributes like `class="F4jsL8"`. They change often and without warning. - -The `product-item` class is simple, human-readable, and semantically connected with the data. The subwoofer is one of the products. A product item. Those are strong signals that this is a good selector. It's also sufficiently unique in the website's context. If the selector was only an `item`, for example, there would be a higher chance that the website's developers would add this class to something unrelated. Like an advertisement. And it could break your extraction code. - -## Extracting data from elements {#extraction-from-elements} - -Now that we found the element, we can start poking into it to extract data. First, let's save the element to a variable so that we can work with it repeatedly. Run these commands in the Console: - -```js -const products = document.querySelectorAll('.product-item'); -const subwoofer = products[2]; -``` - -> If you're wondering what an array is or what `products[2]` means, read the [JavaScript arrays basics](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays). - -Now that we have the subwoofer saved in a variable, run another command in the Console to print its text: - -```js -subwoofer.textContent; -``` - -![Print text content of parent element](./images/devtools-print-parent-text.png) - -As you can see, we were able to extract information about the subwoofer, but the format is still not very useful - there's a lot of content that we don't need. For further processing (ex. in a spreadsheet), we would like to have each piece of data as a separate field (column). To do that, we will look at the HTML structure in more detail. - -### Finding child elements {#finding-child-elements} - -In the [Getting structured data from HTML](#getting-structured-data) section, we were browsing the elements in the **Elements** tab to find the element that contains all the data. We can use the same approach to find the individual data points as well. - -Start from the element that contains all data: `
` Then inspect all the elements nested within this element. You'll discover that: - -- the product's name is an `` element with the class `product-item__title`, and -- the price is held inside a `` with the class `price`. Note that there are two prices. The sale price and the regular price. We want the sale price. - -We will use this knowledge soon to extract the data. - -![Finding child elements in Elements tab](./images/devtools-find-child-elements.png) - -### Selecting child elements {#selecting-child-elements} - -The `document.querySelector()` function looks for a specific element in the whole HTML `document`, so if we called it with `h3`, it would find the first `

` node in the `document`. But we can replace the `document` with any other parent element and the function will limit its search to child elements of the chosen parent. - -Earlier we selected the parent element of the Sony subwoofer and saved it to a variable called `subwoofer`. Let's use this variable to search inside the subwoofer element and find the product's name and price. - -Run two commands in the Console. The first will find the element with the subwoofer's name and save it to a variable called `title`. The second will extract the name and print it. - -```js -const title = subwoofer.querySelector('a.product-item__title'); -title.textContent; -``` - -![Extract product title](./images/devtools-extract-product-title.png) - -Great! We found a way how to programmatically extract the name of the product. We're getting somewhere. - -Next, run the following two commands in the Console. - -```js -const price = subwoofer.querySelector('span.price'); -price.textContent; -``` - -![Extract product price](./images/devtools-extract-product-price.png) - -It worked, but the price was not alone in the result. We extracted it together with some extra text. This is very common in web scraping. Sometimes it's impossible to separate the data we need by element selection alone, and we have to clean the data using other methods. - -### Cleaning extracted data {#cleaning-extracted-data} - -When it comes to data cleaning, there are two main approaches you can take. It's beneficial to understand both, as one approach may be feasible in a given situation while the other is not. - -1. Remove the elements that add noise to your data from the selection. Then extract the pre-cleaned data. -2. Extract the data with noise. Use [regular expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) or other text manipulation techniques to parse the data and keep only the parts we're interested in. - -First, let's look at **removing the noise before extraction**. When you look closely at the element that contains the price, you'll see that it includes another `` element with the text **Sale price**. This `` is what adds noise to our data, and we have to get rid of it. - -![Noise in element selection](./images/devtools-cleaning-noise.png) - -When we call `subwoofer.querySelector('span.price')` it selects the whole `` element that we're not interested in. - -We can, however, use JavaScript to get only the actual text of the selected element, without any child elements. Run this command in the Console: - -```js -price.childNodes[2].nodeValue; -``` - -Why the third child node? Because the first one represents the empty space before `` itself and the third one is the price. In any case, we were able to extract the clean price. - -![Clean price selection](./images/devtools-clean-price.png) - -The second option we have is to **take the noisy price data and clean it with string manipulation**. The data looks like this: - -```text -\n Sale price$158.00 -``` - -This can be approached in a variety of ways. To start let's look at a naive solution: - -```js -price.textContent.split('$')[1]; -``` - -![Split price from noise](./images/devtools-split-price.png) - -And there you go. Notice that this time we extracted the price without the `$` dollar sign. This could be desirable, because we wanted to convert the price from a string to a number, or not, depending on individual circumstances of the scraping project. - -Which method to choose? Neither is the perfect solution. The first method could break if the website's developers change the structure of the `` elements and the price will no longer be in the third position - a very small change that can happen at any moment. - -The second method seems more reliable, but only until the website adds prices in other currency or decides to replace `$` with `USD`. It's up to you, the scraping developer to decide which of the methods will be more resilient on the website you scrape. - -In production, we would probably use a regular expression like the following, or a specialized library for parsing prices from strings, but for this tutorial, we'll keep it simple. - -```js -price.textContent.match(/((\d+,?)+.?(\d+)?)/)[0]; -``` - -## Next up {#next} - -This concludes our lesson on extracting and cleaning data using DevTools. Using CSS selectors, we were able to find the HTML element that contains data about our favorite Sony subwoofer and then extract the data. In the [next lesson](./devtools_continued.md), we will learn how to extract information not only about the subwoofer, but about all the products on the page. diff --git a/sources/academy/webscraping/scraping_basics_legacy/images/beginners-data-collection.png b/sources/academy/webscraping/scraping_basics_legacy/images/beginners-data-collection.png deleted file mode 100644 index a1d2fa9298..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/images/beginners-data-collection.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/images/beginners-data-extraction.png b/sources/academy/webscraping/scraping_basics_legacy/images/beginners-data-extraction.png deleted file mode 100644 index a1d2fa9298..0000000000 Binary files a/sources/academy/webscraping/scraping_basics_legacy/images/beginners-data-extraction.png and /dev/null differ diff --git a/sources/academy/webscraping/scraping_basics_legacy/index.md b/sources/academy/webscraping/scraping_basics_legacy/index.md deleted file mode 100644 index 0e1e45a002..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/index.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Web scraping basics for JavaScript devs (old) -description: Learn how to develop web scrapers with this comprehensive and practical course. Go from beginner to expert, all in one place. -sidebar_position: 8 -sidebar_label: Web scraping basics with JS (old) -category: web scraping -slug: /scraping-basics-javascript/legacy -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../scraping_basics/_legacy.mdx'; - -**Learn how to develop web scrapers with this comprehensive and practical course. Go from beginner to expert, all in one place.** - - - ---- - -Welcome to **Web scraping basics for JavaScript devs**, a comprehensive, practical and long form web scraping course that will take you from an absolute beginner to a successful web scraper developer. If you're looking for a quick start, we recommend trying [this tutorial](https://blog.apify.com/web-scraping-javascript-nodejs/) instead. - -This course is made by [Apify](https://apify.com), the web scraping and automation platform, but we will use only open-source technologies throughout all academy lessons. This means that the skills you learn will be applicable to any scraping project, and you'll be able to run your scrapers on any computer. No Apify account needed. - -If you would like to learn about the Apify platform and how it can help you build, run and scale your web scraping and automation projects, see the [Apify platform course](../../platform/apify_platform.md), where we'll teach you all about Apify serverless infrastructure, proxies, API, scheduling, webhooks and much more. - -## Why learn scraper development {#why-learn} - -With so many point-and-click tools and no-code software that can help you extract data from websites, what is the point of learning web scraper development? Contrary to what their marketing departments say, a point-and-click or no-code tool will never be as flexible, as powerful, or as optimized as a custom-built scraper. - -Any software can do only what it was programmed to do. If you build your own scraper, it can do anything you want. And you can always quickly change it to do more, less, or the same, but faster or cheaper. The possibilities are endless once you know how scraping really works. - -Scraper development is a fun and challenging way to learn web development, web technologies, and understand the internet. You will reverse-engineer websites and understand how they work internally, what technologies they use and how they communicate with their servers. You will also master your chosen programming language and core programming concepts. When you truly understand web scraping, learning other technologies like React or Next.js will be a piece of cake. - -## Course summary {#summary} - -When we set out to create the Academy, we wanted to build a complete guide to web scraping - a course that a beginner could use to create their first scraper, as well as a resource that professionals will continuously use to learn about advanced and niche web scraping techniques and technologies. All lessons include code examples and code-along exercises that you can use to immediately put your scraping skills into action. - -This is what you'll learn in the **Web scraping basics for JavaScript devs** course: - -* [Web scraping basics for JavaScript devs](./index.md) - * [Basics of data extraction](./data_extraction/index.md) - * [Basics of crawling](./crawling/index.md) - * [Best practices](./best_practices.md) - -## Requirements {#requirements} - -You don't need to be a developer or a software engineer to complete this course, but basic programming knowledge is recommended. Don't be afraid, though. We explain everything in great detail in the course and provide external references that can help you level up your web scraping and web development skills. If you're new to programming, pay very close attention to the instructions and examples. A seemingly insignificant thing like using `[]` instead of `()` can make a lot of difference. - -> If you don't already have basic programming knowledge and would like to be well-prepared for this course, we recommend learning about [JavaScript basics](https://developer.mozilla.org/en-US/curriculum/core/javascript-fundamentals/) and [CSS Selectors](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors). - -As you progress to the more advanced courses, the coding will get more challenging, but will still be manageable to a person with an intermediate level of programming skills. - -Ideally, you should have at least a moderate understanding of the following concepts: - -### JavaScript + Node.js {#javascript-and-node} - -It is recommended to understand at least the fundamentals of JavaScript and be proficient with Node.js prior to starting this course. If you are not yet comfortable with asynchronous programming (with promises and `async...await`), loops (and the different types of loops in JavaScript), modularity, or working with external packages, we would recommend studying the following resources before coming back and continuing this section: - -* [`async...await` (YouTube)](https://www.youtube.com/watch?v=vn3tm0quoqE&ab_channel=Fireship) -* [JavaScript loops (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration) -* [Modularity in Node.js](https://javascript.plainenglish.io/how-to-use-modular-patterns-in-nodejs-982f0e5c8f6e) - -### General web development {#general-web-development} - -Throughout the next lessons, we will sometimes use certain technologies and terms related to the web without explaining them. This is because their knowledge will be **assumed** (unless we're showing something out of the ordinary). - -* [HTML](https://developer.mozilla.org/en-US/docs/Web/HTML) -* [HTTP protocol](https://developer.mozilla.org/en-US/docs/Web/HTTP) -* [DevTools](./data_extraction/browser_devtools.md) - -### jQuery or Cheerio {#jquery-or-cheerio} - -We'll be using the [**Cheerio**](https://www.npmjs.com/package/cheerio) package a lot to parse data from HTML. This package provides an API using jQuery syntax to help traverse downloaded HTML within Node.js. - -## Next up {#next} - -The course begins with a small bit of theory and moves into some realistic and practical examples of extracting data from the most popular websites on the internet using your browser console. [Let's get to it!](./introduction.md) - -> If you already have experience with HTML, CSS, and browser DevTools, feel free to skip to the [Basics of crawling](./crawling/index.md) section. diff --git a/sources/academy/webscraping/scraping_basics_legacy/introduction.md b/sources/academy/webscraping/scraping_basics_legacy/introduction.md deleted file mode 100644 index c2a8bde1ec..0000000000 --- a/sources/academy/webscraping/scraping_basics_legacy/introduction.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Introduction -description: Start learning about web scraping, web crawling, data extraction, and popular tools to start developing your own scraper. -sidebar_position: 1.1 -category: courses -slug: /scraping-basics-javascript/legacy/introduction -pagination: true -noindex: true ---- - -import LegacyAdmonition from '../scraping_basics/_legacy.mdx'; - -**Start learning about web scraping, web crawling, data extraction, and popular tools to start developing your own scraper.** - - - ---- - -Web scraping or crawling? Web data extraction, mining, or collection? You can find various definitions on the web. Let's agree on explanations that we will use throughout this beginner course on web scraping. - -## What is web data extraction? {#what-is-data-extraction} - -Web data extraction (or collection) is a process that takes a web page, like an Amazon product page, and collects useful information from the page, such as the product's name and price. Web pages are an unstructured data source and the goal of web data extraction is to make information from websites structured, so that it can be processed by data analysis tools or integrated with computer systems. The main sources of data on a web page are HTML documents and API calls, but also images, PDFs, etc. - -![product data extraction from Amazon](./images/beginners-data-extraction.png) - -## What is crawling? {#what-is-crawling} - -Where web data extraction focuses on a single page, web crawling (sometimes called spidering ๐Ÿ•ท) is all about movement between pages or websites. The purpose of crawling is to travel across the website to find pages with the information we want. Crawling and collection can happen either simultaneously, while moving from page to page, or separately, where one scraper focuses solely on finding pages with data, and another scraper collects the data. The main purpose of crawling is to collect URLs or other links that can be used to move around. - -## What is web scraping? {#what-is-web-scraping} - -We use web scraping as an umbrella term for crawling, web data extraction and all other activities that have the purpose of converting unstructured data from the web to a structured format ready for integration or data analysis. In the advanced courses, you'll learn that web scraping is about much more than just HTML and URLs. - -## Next up {#next} - -In the [next lesson](./data_extraction/index.md), you will learn about the basic building blocks of each web page. HTML, CSS and JavaScript. diff --git a/src/components/LegacyJsCourseAdmonition.jsx b/src/components/LegacyJsCourseAdmonition.jsx deleted file mode 100644 index a688e1e380..0000000000 --- a/src/components/LegacyJsCourseAdmonition.jsx +++ /dev/null @@ -1,24 +0,0 @@ -import { useLocation } from '@docusaurus/router'; -import Admonition from '@theme/Admonition'; - -export default function LegacyJsCourseAdmonition({ param = 'legacy-js-course' }) { - const location = useLocation(); - const params = new URLSearchParams(location.search); - const value = params.get(param); - if (!value) return null; - return ( -
- -

- You're trying to access page {value} from our old{' '} - Web scraping basics for JavaScript devs course, which is now archived. -

-

- You can still read that page, but - we recommend you to check out this new course instead. We plan to completely retire the old course - in a few months. -

- -
- ); -}