Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(academy): add advanced crawling section with sitemaps and search #1217

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
Open
3 changes: 3 additions & 0 deletions nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,9 @@ server {
rewrite ^/platform/actors/development/actor-definition/output-schema$ /platform/actors/development/actor-definition/dataset-schema permanent;
rewrite ^academy/deploying-your-code/output-schema$ /academy/deploying-your-code/dataset-schema permanent;

# Academy restructuring
rewrite ^academy/advanced-web-scraping/scraping-paginated-sites$ /academy/advanced-web-scraping/crawling/crawling-with-search permanent;

# Removed pages
# GPT plugins were discontinued April 9th, 2024 - https://help.openai.com/en/articles/8988022-winding-down-the-chatgpt-plugins-beta
rewrite ^/platform/integrations/chatgpt-plugin$ https://blog.apify.com/add-custom-actions-to-your-gpts/ redirect;
Expand Down
14 changes: 14 additions & 0 deletions sources/academy/tutorials/node_js/scraping_from_sitemaps.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,20 @@ import Example from '!!raw-loader!roa-loader!./scraping_from_sitemaps.js';

# How to scrape from sitemaps {#scraping-with-sitemaps}

:::note
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

Crawlee allows you to scrape sitemaps with ease. If you are using Crawlee, you can skip the following steps and just gather all the URLs from the sitemap in a few lines of code.

:::

```js
import { RobotsFile } from 'crawlee';

const robots = await RobotsFile.find('https://www.mysite.com');

const allWebsiteUrls = await robots.parseUrlsFromSitemaps();
```

**The sitemap.xml file is a jackpot for every web scraper developer. Take advantage of this and learn an easier way to extract data from websites using Crawlee.**

---
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
---
title: Crawling sitemaps
description: Learn how to extract all of a website's listings even if they limit the number of results pages. See code examples for setting up your scraper.
sidebar_position:: 2
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved
slug: /advanced-web-scraping/crawling/crawling-sitemaps
---

In the previous lesson, we learned what is the utility (and dangers) of crawling sitemaps. In this lesson, we will go in-depth to how to crawl sitemaps.

We will look at the following topics:

- How to find sitemap URLs
- How to set up HTTP requests to download sitemaps
- How to parse URLs from sitemaps
- Using Crawlee to get all URLs in a few lines of code

## How to find sitemap URLs

Sitemaps are commonly restricted to contain a maximum of 50k URLs so usually, there will be a whole list of them. There can be a master sitemap containing URLs of all other sitemaps or the sitemaps might simply be indexed in robots.txt and/or have auto-incremented URLs like `/sitemap1.xml`, `/sitemap2.xml`, etc.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

### Google

You can try your luck on Google by searching for `site:example.com sitemap.xml` or `site:example.com sitemap.xml.gz` and see if you get any results. If you do, you can try to download the sitemap and see if it contains any useful URLs. The success of this approach depends on the website telling Google to index the sitemap file itself which is rather uncommon.

### robots.txt {#robots-txt}

If the website has a robots.txt file, it often contains sitemap URLs. The sitemap URLs are usually listed under `Sitemap:` directive.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

### Common URL paths

You can try to iterate over common URL paths like:
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

- /sitemap.xml
- /product_index.xml
- /product_template.xml
- /sitemap_index.xml
- /sitemaps/sitemap_index.xml
- /sitemap/product_index.xml
- /media/sitemap.xml
- /media/sitemap/sitemap.xml
- /media/sitemap/index.xml

Make also sure you test the list with `.gz`, `.tar.gz` and `.tgz` extensions and by capitalizing the words (e.g. `/Sitemap_index.xml.tar.gz`).

Some websites also provide an HTML version, to help indexing bots find new content. Those include:
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

- /sitemap
- /category-sitemap
- /sitemap.html
- /sitemap_index

Apify provides the [Sitemap Sniffer actor](https://apify.com/vaclavrut/sitemap-sniffer) (open-source code), that scans the URL variations automatically for you so that you don't have to check manually.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

## How to set up HTTP requests to download sitemaps

For most sitemaps, you can make a simple HTTP request and parse the downloaded XML text with Cheerio (or just use `CheerioCrawler`). Some sitemaps are compressed and have to be streamed and decompressed. The code for that is fairly complicated so we recommend just [using Crawlee](#using-crawlee) which handles streamed and compressed sitemaps by default.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

## How to parse URLs from sitemaps

The easiest part is to parse the actual URLs from the sitemap. The URLs are usually listed under `<loc>` tags. You can use Cheerio to parse the XML text and extract the URLs. Just be careful that the sitemap might contain other URLs that you don't want to crawl (e.g. /about, /contact, or various special category sections). [This article](/academy/node-js/scraping-from-sitemaps) provides code examples for parsing sitemaps.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

## Using Crawlee

Fortunately, you don't have to worry about any of the above steps if you use [Crawlee](https://crawlee.dev) which has rich traversing and parsing support for sitemap. Crawlee can traverse nested sitemaps, download, and parse compressed sitemaps, and extract URLs from them. You can get all URLs in a few lines of code:
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

```js
import { RobotsFile } from 'crawlee';

const robots = await RobotsFile.find('https://www.mysite.com');

const allWebsiteUrls = await robots.parseUrlsFromSitemaps();
```

## Next up

That's all we need to know about sitemaps for now. Let's dive into a much more interesting topic - search, filters, and pagination.
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
---
title: Overcoming pagination limits
title: Crawling with search
description: Learn how to extract all of a website's listings even if they limit the number of results pages. See code examples for setting up your scraper.
sidebar_position: 1
slug: /advanced-web-scraping/scraping-paginated-sites
sidebar_position:: 3
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved
slug: /advanced-web-scraping/crawling/crawling-with-search
---

# Scraping websites with limited pagination
# Scraping websites with search

**Learn how to extract all of a website's listings even if they limit the number of results pages. See code examples for setting up your scraper.**
In this lesson, we will start with a simpler example of scraping HTML based websites with limited pagination.

---

Limited pagination is a common practice on e-commerce sites and is becoming more popular over time. It makes sense: a real user will never want to look through more than 200 pages of results, only bots love unlimited pagination. Fortunately, there are ways to overcome this limit while keeping our code clean and generic.
Limited pagination is a common practice on e-commerce sites and is becoming more popular over time. It makes sense: a real user will never want to look through more than 200 pages of results – only bots love unlimited pagination. Fortunately, there are ways to overcome this limit while keeping our code clean and generic.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

![Pagination in on Google search results page](./images/pagination.png)

Expand Down Expand Up @@ -283,7 +281,6 @@ await crawler.addRequests(requestsToEnqueue);

## Summary {#summary}

And that's it. We have an elegant solution to a complicated problem. In a real project, you would want to make this a bit more robust and [save analytics data](../../platform/expert_scraping_with_apify/saving_useful_stats.md). This will let you know what filters you went through and how many products each of them had.
And that's it. We have an elegant solution for a complicated problem. In a real project, you would want to make this a bit more robust and [save analytics data](../../../platform/expert_scraping_with_apify/saving_useful_stats.md). This will let you know what filters you went through and how many products each of them had.

Check out the [full code example](https://github.com/apify-projects/apify-extra-library/tree/master/examples/crawler-with-filters).

Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
---
title: Sitemaps vs search
description: Learn how to extract all of a website's listings even if they limit the number of results pages.
sidebar_position:: 1
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved
slug: /advanced-web-scraping/crawling/sitemaps-vs-search
---

The core crawling problem comes to down to ensuring that we reliably find all detail pages on the target website or inside its categories. This is trivial for small sites. We just open the home page or category pages and paginate to the end as we did in the Web Scraping for Beginners course.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

Unfortunately, **most modern websites restrict pagination** only to somewhere between 1 and 10 000 products. Solving this problem might seem relatively straightforward at first but there are multiple hurdles that we will explore in this lesson.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

There are two main approaches to solving this problem:

- Extracting all page URLs from the website's **sitemap**.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved
- Using **categories, search and filters** to split the website so we get under the pagination limit.

Both of these approaches have their pros and cons so the best solution is to **use both and combine the results**. Here we will learn why.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

## Pros and cons of sitemaps

Sitemap is usually a simple XML file that contains a list of all pages on the website. They are created and maintained mainly for search engines like Google to help ensure that the website gets fully indexed there. They are commonly located at URLs like `https://example.com/sitemap.xml` or `https://example.com/sitemap.xml.gz`. We will get to work with sitemaps in the next lesson.

### Pros

- **Quick to set up** - The logic to find all sitemaps and extract all URLs is usually simple and can be done in a few lines of code.
- **Fast to run** - You only need to run a single request for each sitemap that contains up to 50,000 URLs. This means you can get all the URLs in a matter of seconds.
- **Usually complete** - Websites have an incentive to keep their sitemaps up to date as they are used by search engines. This means that they usually contain all pages on the website.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

### Cons

- **Does not directly reflect the website** - There is no way you can ensure that all pages on the website are in the sitemap. The sitemap also can contain pages that were already removed and will return 404s. This is a major downside of sitemaps which prevents us from using them as the only source of URLs.
- **Updated in intervals** - Sitemaps are usually not updated in real-time. This means that you might miss some pages if you scrape them too soon after they were added to the website. Common update intervals are 1 day or 1 week.
- **Hard to find or unavailable** - Sitemaps are not always trivial to locate. They can be deployed on a CDN with unpredictable URLs. Sometimes they are not available at all.
- **Streamed, compressed, and archived** - Sitemaps are often streamed and archived with .tgz extensions and compressed with gzip. This means that you cannot use default HTTP client settings and must handle these cases with extra code. Fortunately, we will get to this in the next lesson.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

## Pros and cons of categories, search, and filters

This approach means traversing the website like a normal user do by going through categories, setting up different filters, ranges and sorting options. The goal is to traverse it is a way that ensures we covered all categories/ranges where products can be located and for each of those we stayed under the pagination limit.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

The pros and cons of this approach are pretty much the opposite of the sitemaps approach.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

### Pros

- **Directly reflects the website** - With most scraping use-cases, we want to analyze the website as the regular users see it. By going through the intended user flow, we ensure that we are getting the same pages as the users.
- **Updated in real-time** - The website is updated in real-time so we can be sure that we are getting all pages.
- **Often contain detailed data** - While sitemaps are usually just a list of URLs, categories, searches and filters often contain additional data like product names, prices, categories, etc, especially if available via JSON API. This means that we can sometimes get all the data we need without going to the detail pages.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

### Cons

- **Complex to set up** - The logic to traverse the website is usually more complex and can take a lot of time to get right. We will get to this in the next lessons.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved
- **Slow to run** - The traversing can require a lot of requests. Some filters or categories will have products we already found.
- **Not always complete** - Sometimes the combination of filters and categories will not allow us to ensure we have all products. This is especially painful for sites where we don't know the exact number of products we are looking for. The framework we will build in the next lessons will help us with this.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

## Do we know how many products there are?

Fortunately, most websites list a total number of detail pages somewhere. It might be displayed on the home page or search results or be provided in the API response. We just need to make sure that this number really represents the whole site or category we are looking to scrape. By knowing the total number of products, we can tell if our approach to scrape all succeeded or if we still need to refine it.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

Unfortunately, some sites like Amazon do not provide exact numbers. In this case, we have to work with what they give us and put even more effort into making our scraping logic accurate. We will tackle this in the next lessons as well.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

## Next up

First, we will look into the easier approach, the [sitemap crawling](./crawling-sitemaps.md). Then we will go through all the intricacies of the category, search and filter crawling, and build up a generic framework that we can use on any website. At last, we will combine the results of both approaches and set up monitoring and persistence to ensure we can run this regularly without any manual controls.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved
24 changes: 17 additions & 7 deletions sources/academy/webscraping/advanced_web_scraping/index.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,31 @@
---
title: Advanced web scraping
description: Take your scrapers to the next level by learning various advanced concepts and techniques that will help you build highly scalable and reliable crawlers.
sidebar_position: 6
description: Take your scrapers to a production-ready level by learning various advanced concepts and techniques that will help you build highly scalable and reliable crawlers.
sidebar_position:: 6
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved
category: web scraping & automation
slug: /advanced-web-scraping
---

# Advanced web scraping
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

**Take your scrapers to the next level by learning various advanced concepts and techniques that will help you build highly scalable and reliable crawlers.**
In [**Web scraping for beginners**](/academy/web-scraping-for-beginners) course, we have learned the necessary basics required to create a scraper. In the following courses, we learned more about specific practices and techniques that will help us to solve most of the problems we will face.
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

---
In this course, we will take all of that knowledge, add a few more advanced concepts, and apply them to learn how to build a production-ready web scraper.

## What does production-ready mean

To scrape large and complex websites, we need to scale two essential aspects of the scraper: crawling and data extraction. Big websites can have millions of pages and the data we want to extract requires more sophisticated parsing techniques than just selecting elements by CSS selectors or using APIs as they are.

<!--
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved
The following sections will cover the core concepts that will ensure that your scraper is production-ready:
The advanced crawling section will cover how to ensure we find all pages or products on the website.
- The advanced data extraction will cover how to efficiently extract data from a particular page or API.
-->

In this course, we'll be tackling some of the most challenging and advanced web-scraping cases, such as mobile-app scraping, scraping sites with limited pagination, and handling large-scale cases where millions of items are scraped. Are **you** ready to take your scrapers to the next level?
We will also touch on monitoring, performance, anti-scraping protections, and debugging.

If you've managed to follow along with all of the courses prior to this one, then you're more than ready to take these upcoming lessons on 😎

## First up {#first-up}
## First up

This course's [first lesson](./scraping_paginated_sites.md) dives head-first into one of the most valuable skills you can have as a scraper developer: **Scraping paginated sites**.
First, we will explore [advanced crawling section](./crawling/sitemaps-vs-search.md) that will help us to find all pages or products on the website.
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ Here's what the output of this code looks like:

## Final note {#final-note}
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

Sometimes, APIs have limited pagination. That means that they limit the total number of results that can appear for a set of pages, or that they limit the pages to a certain number. To learn how to handle these cases, take a look at [this short article](/academy/advanced-web-scraping/scraping-paginated-sites).
Sometimes, APIs have limited pagination. That means that they limit the total number of results that can appear for a set of pages, or that they limit the pages to a certain number. To learn how to handle these cases, take a look at [this short article](/academy/advanced-web-scraping/crawling/crawling-with-search).
metalwarrior665 marked this conversation as resolved.
Show resolved Hide resolved

## Next up {#next}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import TabItem from '@theme/TabItem';

If you're trying to [collect data](../executing_scripts/extracting_data.md) on a website that has millions, thousands, or even hundreds of results, it is very likely that they are paginating their results to reduce strain on their back-end as well as on the users loading and rendering the content.

![Amazon pagination](../../advanced_web_scraping/images/pagination.png)
![Amazon pagination](../../advanced_web_scraping/crawling/images/pagination.png)

## Page number-based pagination {#page-number-based-pagination}

Expand Down
Loading