目次
インストール
ホームページ バックエンド開発 Python チュートリアル Pythonで無限スクロールWebページをスクレイピングする方法

Pythonで無限スクロールWebページをスクレイピングする方法

Aug 28, 2024 pm 06:33 PM

Pythonで無限スクロールWebページをスクレイピングする方法

こんにちは、Crawlee 開発者の皆さん、Crawlee ブログの別のチュートリアルへようこそ。このチュートリアルでは、Crawlee for Python を使用して無限スクロール Web サイトをスクレイピングする方法を説明します。

コンテキストとしては、無限スクロール ページは、古典的なページネーションに代わる最新の方法です。ユーザーが次のページを選択せず​​に Web ページの一番下までスクロールすると、ページには自動的に追加のデータが読み込まれ、ユーザーはさらにスクロールできるようになります。

大のスニーカーマニアとして、ナイキ シューズの無限スクロール Web サイトを例として取り上げ、そこから何千ものスニーカーをかき集めます。

Crawlee for Python には、HTTP およびヘッドレス ブラウザ クロール用の統合インターフェイス、自動再試行など、いくつかの素晴らしい初期機能があります。

前提条件とプロジェクトのブートストラップ

次のコマンドを使用して Crawlee for Python をインストールして、チュートリアルを開始しましょう:

pipx run crawlee create nike-crawler

このブログを読む前に、GitHub で Crawlee for Python にスターを付けていただければ大変嬉しく思います!

How to scrape infinite scrolling webpages with Python アピファイ / クローリーパイソン

Crawlee - 信頼性の高いクローラを構築するための Python 用の Web スクレイピングおよびブラウザ自動化ライブラリ。 AI、LLM、RAG、または GPT のデータを抽出します。 HTML、PDF、JPG、PNG、その他のファイルを Web サイトからダウンロードします。 BeautifulSoup、Playwright、生の HTTP で動作します。ヘッドフルモードとヘッドレスモードの両方。プロキシローテーションあり。

How to scrape infinite scrolling webpages with Python
Webスクレイピングとブラウザ自動化ライブラリ

How to scrape infinite scrolling webpages with Python How to scrape infinite scrolling webpages with Python How to scrape infinite scrolling webpages with Python How to scrape infinite scrolling webpages with Python

Crawlee はクローリングとスクレイピングをエンドツーエンドでカバーし、信頼性の高いスクレーパーの構築を支援します。早いです。

? Crawlee for Python は早期採用者に公開されています!

あなたのクローラーはほとんど人間のように見え、デフォルト設定であっても最新のボット保護のレーダーの下を飛行します。 Crawlee は、技術的な詳細を気にすることなく、Web をクロールしてリンクを探し、データを収集し、機械可読形式で永続的に保存するためのツールを提供します。また、豊富な構成オプションのおかげで、デフォルト設定では不十分な場合でも、プロジェクトのニーズに合わせて Crawlee のほぼすべての側面を調整できます。

? Crawlee プロジェクト Web サイトで完全なドキュメント、ガイド、例を表示します ?

Crawlee の TypeScript 実装もあります。これを探索してプロジェクトに活用できます。詳細については、GitHub の Crawlee for JS/TS の GitHub リポジトリにアクセスしてください。

インストール

私たちは…


GitHub で表示


We will scrape using headless browsers. Select PlaywrightCrawler in the terminal when Crawlee for Python asks for it.

After installation, Crawlee for Python will create boilerplate code for you. Redirect into the project folder and then run this command for all the dependencies installation:

poetry install

How to scrape infinite scrolling webpages

  1. Handling accept cookie dialog

  2. Adding request of all shoes links

  3. Extract data from product details

  4. Accept Cookies context manager

  5. Handling infinite scroll on the listing page

  6. Exporting data to CSV format

Handling accept cookie dialog

After all the necessary installations, we'll start looking into the files and configuring them accordingly.

When you look into the folder, you'll see many files, but for now, let’s focus on main.py and routes.py.

In __main__.py, let's change the target location to the Nike website. Then, just to see how scraping will happen, we'll add headless = False to the PlaywrightCrawler parameters. Let's also increase the maximum requests per crawl option to 100 to see the power of parallel scraping in Crawlee for Python.

The final code will look like this:

import asyncio

from crawlee.playwright_crawler import PlaywrightCrawler

from .routes import router


async def main() -> None:

    crawler = PlaywrightCrawler(
        headless=False,
        request_handler=router,
        max_requests_per_crawl=100,
    )

    await crawler.run(
        [
            'https://nike.com/,
        ]
    )


if __name__ == '__main__':
    asyncio.run(main())

Now coming to routes.py, let’s remove:

await context.enqueue_links()

As we don’t want to scrape the whole website.

Now, if you run the crawler using the command:

poetry run python -m nike-crawler

As the cookie dialog is blocking us from crawling more than one page's worth of shoes, let’s get it out of our way.

We can handle the cookie dialog by going to Chrome dev tools and looking at the test_id of the "accept cookies" button, which is dialog-accept-button.

Now, let’s remove the context.push_data call that was left there from the project template and add the code to accept the dialog in routes.py. The updated code will look like this:

from crawlee.router import Router
from crawlee.playwright_crawler import PlaywrightCrawlingContext

router = Router[PlaywrightCrawlingContext]()

@router.default_handler
async def default_handler(context: PlaywrightCrawlingContext) -> None:

    # Wait for the popup to be visible to ensure it has loaded on the page.
    await context.page.get_by_test_id('dialog-accept-button').click()

Adding request of all shoes links

Now, if you hover over the top bar and see all the sections, i.e., man, woman, and kids, you'll notice the “All shoes” section. As we want to scrape all the sneakers, this section interests us. Let’s use get_by_test_id with the filter of has_text=’All shoes’ and add all the links with the text “All shoes” to the request handler. Let’s add this code to the existing routes.py file:

    shoe_listing_links = (
        await context.page.get_by_test_id('link').filter(has_text='All shoes').all()
    )
    await context.add_requests(
        [
            Request.from_url(url, label='listing')
            for link in shoe_listing_links
            if (url := await link.get_attribute('href'))
        ]
    )

@router.handler('listing')
async def listing_handler(context: PlaywrightCrawlingContext) -> None:
    """Handler for shoe listings."""

Extract data from product details

Now that we have all the links to the pages with the title “All Shoes,” the next step is to scrape all the products on each page and the information provided on them.

We'll extract each shoe's URL, title, price, and description. Again, let's go to dev tools and extract each parameter's relevant test_id. After scraping each of the parameters, we'll use the context.push_data function to add it to the local storage. Now let's add the following code to the listing_handler and update it in the routes.py file:

@router.handler('listing')
async def listing_handler(context: PlaywrightCrawlingContext) -> None:
    """Handler for shoe listings."""        

    await context.enqueue_links(selector='a.product-card__link-overlay', label='detail')


@router.handler('detail')
async def detail_handler(context: PlaywrightCrawlingContext) -> None:
    """Handler for shoe details."""

    title = await context.page.get_by_test_id(
        'product_title',
    ).text_content()

    price = await context.page.get_by_test_id(
        'currentPrice-container',
    ).first.text_content()

    description = await context.page.get_by_test_id(
        'product-description',
    ).text_content()

    await context.push_data(
        {
            'url': context.request.loaded_url,
            'title': title,
            'price': price,
            'description': description,
        }
    )

Accept Cookies context manager

Since we're dealing with multiple browser pages with multiple links and we want to do infinite scrolling, we may encounter an accept cookie dialog on each page. This will prevent loading more shoes via infinite scroll.

We'll need to check for cookies on every page, as each one may be opened with a fresh session (no stored cookies) and we'll get the accept cookie dialog even though we already accepted it in another browser window. However, if we don't get the dialog, we want the request handler to work as usual.

To solve this problem, we'll try to deal with the dialog in a parallel task that will run in the background. A context manager is a nice abstraction that will allow us to reuse this logic in all the router handlers. So, let's build a context manager:

from playwright.async_api import TimeoutError as PlaywrightTimeoutError

@asynccontextmanager
async def accept_cookies(page: Page):
    task = asyncio.create_task(page.get_by_test_id('dialog-accept-button').click())
    try:
        yield
    finally:
        if not task.done():
            task.cancel()

        with suppress(asyncio.CancelledError, PlaywrightTimeoutError):
            await task

This context manager will make sure we're accepting the cookie dialog if it exists before scrolling and scraping the page. Let’s implement it in the routes.py file, and the updated code is here

Handling infinite scroll on the listing page

Now for the last and most interesting part of the tutorial! How to handle the infinite scroll of each shoe listing page and make sure our crawler is scrolling and scraping the data constantly.

To handle infinite scrolling in Crawlee for Python, we just need to make sure the page is loaded, which is done by waiting for the network_idle load state, and then use the infinite_scroll helper function which will keep scrolling to the bottom of the page as long as that makes additional items appear.

Let’s add two lines of code to the listing handler:

@router.handler('listing')
async def listing_handler(context: PlaywrightCrawlingContext) -> None:
    # Handler for shoe listings

    async with accept_cookies(context.page):
        await context.page.wait_for_load_state('networkidle')
        await context.infinite_scroll()
        await context.enqueue_links(
            selector='a.product-card__link-overlay', label='detail'
        )

Exporting data to CSV format

As we want to store all the shoe data into a CSV file, we can just add a call to the export_data helper into the __main__.py file just after the crawler run:

await crawler.export_data('shoes.csv')

Working crawler and its code

Now, we have a crawler ready that can scrape all the shoes from the Nike website while handling infinite scrolling and many other problems, like the cookies dialog.

You can find the complete working crawler code here on the GitHub repository.

If you have any doubts regarding this tutorial or using Crawlee for Python, feel free to join our discord community and ask fellow developers or the Crawlee team.

Crawlee & Apify

This is the official developer community of Apify and Crawlee. | 8365 members

How to scrape infinite scrolling webpages with Python discord.com

This tutorial is taken from the webinar held on August 5th where Jan Buchar, Senior Python Engineer at Apify, gave a live demo about this use case. Watch the whole webinar here.

以上がPythonで無限スクロールWebページをスクレイピングする方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

ホットトピック

完成したPython Blockbuster Online Viewing Entrant Python無料完成ウェブサイトコレクション 完成したPython Blockbuster Online Viewing Entrant Python無料完成ウェブサイトコレクション Jul 23, 2025 pm 12:36 PM

この記事では、いくつかのトップPython「完成した」プロジェクトWebサイトと、高レベルの「大ヒット作「学習リソースポータル」が選択されています。開発のインスピレーション、観察、学習のマスターレベルのソースコードを探している場合でも、実用的な機能を体系的に改善している場合でも、これらのプラットフォームは見逃せず、Pythonマスターに迅速に成長するのに役立ちます。

Python Run Shellコマンドの例 Python Run Shellコマンドの例 Jul 26, 2025 am 07:50 AM

subprocess.run()を使用して、シェルコマンドを安全に実行し、出力をキャプチャします。注入リスクを避けるために、リストのパラメーターを渡すことをお勧めします。 2。シェル特性が必要な場合は、シェル= trueを設定できますが、コマンドインジェクションに注意してください。 3. subprocess.popenを使用して、リアルタイム出力処理を実現します。 4。Check = COMMATが失敗したときに例外をスローするためにtrueを設定します。 5.単純なシナリオで直接チェーンを呼び出して出力を取得できます。 os.system()または非推奨モジュールの使用を避けるために、日常生活の中でsubprocess.run()を優先する必要があります。上記の方法は、Pythonでシェルコマンドを実行するコアの使用を上書きします。

Python Seabornジョイントプロットの例 Python Seabornジョイントプロットの例 Jul 26, 2025 am 08:11 AM

Seabornのジョイントプロットを使用して、2つの変数間の関係と分布をすばやく視覚化します。 2。基本的な散布図は、sns.jointplot(data = tips、x = "total_bill"、y = "tip"、dind = "scatter")によって実装され、中心は散布図であり、ヒストグラムは上部と右側と右側に表示されます。 3.回帰線と密度情報をdind = "reg"に追加し、marminal_kwsを組み合わせてエッジプロットスタイルを設定します。 4。データ量が大きい場合は、「ヘックス」を使用することをお勧めします。

python httpx asyncクライアントの例 python httpx asyncクライアントの例 Jul 29, 2025 am 01:08 AM

httpx.asyncclientを使用して、非同期httpリクエストを効率的に開始します。 1.基本的なGETリクエストは、asyncwithを介してクライアントを管理し、awaitclient.getを使用して非ブロッキングリクエストを開始します。 2。asyncio.gatherを組み合わせてasyncio.gatherを組み合わせると、パフォーマンスが大幅に向上する可能性があり、合計時間は最も遅いリクエストに等しくなります。 3.カスタムヘッダー、認証、base_url、タイムアウト設定をサポートします。 4。投稿リクエストを送信してJSONデータを伝達できます。 5.同期非同期コードの混合を避けるために注意してください。プロキシサポートは、クローラーやAPI集約、その他のシナリオに適したバックエンド互換性に注意を払う必要があります。

パイソンリストへの変換の例 パイソンリストへの変換の例 Jul 26, 2025 am 08:00 AM

文字列リストは、 '' .join(words)などのJoIn()メソッドとマージして、「Helloworldfrompython」を取得できます。 2。NUMBERリストは、参加する前にMAP(STR、数字)または[STR(x)forxinNumbers]を備えた文字列に変換する必要があります。 3.任意のタイプリストは、デバッグに適したブラケットと引用符のある文字列に直接変換できます。 4。カスタム形式は、 '|' .join(f "[{item}]" foriteminitems)output "[a] | [などのjoin()と組み合わせたジェネレーター式によって実装できます。

メモリバウンド操作のためのPythonの最適化 メモリバウンド操作のためのPythonの最適化 Jul 28, 2025 am 03:22 AM

Pythoncanbeoptimizedformemory-boundoperationsは、ヘッドゲネレーター、EfficientDataStructures、およびManagingObjectlifetimes.first、Usegeneratoratoratoratoratoratoraturatussを使用していることを確認してください

PythonはSQL Server Pyodbcの例に接続します PythonはSQL Server Pyodbcの例に接続します Jul 30, 2025 am 02:53 AM

Pyodbcのインストール:Pipinstallpyodbcコマンドを使用してライブラリをインストールします。 2.接続sqlserver:pyodbc.connect()メソッドを介して、ドライバー、サーバー、データベース、uid/pwdまたはtrusted_connectionを含む接続文字列を使用し、それぞれSQL認証またはWindows認証をサポートします。 3.インストールされているドライバーを確認します:pyodbc.drivers()を実行し、「sqlserver」を含むドライバー名をフィルタリングして、「sqlserverのodbcdriver17」などの正しいドライバー名が使用されるようにします。 4.接続文字列の重要なパラメーター

python shotil rmtreeの例 python shotil rmtreeの例 Aug 01, 2025 am 05:47 AM

shutil.rmtree()は、ディレクトリツリー全体を再帰的に削除するPythonの関数です。指定されたフォルダーとすべてのコンテンツを削除できます。 1.基本的な使用法:shutil.rmtree(PATH)を使用してディレクトリを削除すると、FilenotFounderror、PermissionError、その他の例外を処理する必要があります。 2。実用的なアプリケーション:一時的なデータやキャッシュディレクトリなど、サブディレクトリとファイルを1回クリックして含むフォルダーをクリアできます。 3。注:削除操作は復元されません。 FilenotFounderrorは、パスが存在しない場合に投げられます。許可またはファイル職業のために失敗する可能性があります。 4.オプションのパラメーター:INGRORE_ERRORS = trueでエラーを無視できます

See all articles