検索
ホームページバックエンド開発Python チュートリアルCrawlee を使用して Python で LinkedIn ジョブ スクレーパーを作成する方法

導入

この記事では、Crawlee と Streamlit を使用して、LinkedIn をスクレイピングして求人情報を取得する Web アプリケーションを構築します。

Crawlee for Python を使用して、Python で LinkedIn 求人スクレーパーを作成し、Web アプリケーションを通じて動的に受信したユーザー入力から会社名、役職、投稿時刻、求人情報へのリンクを抽出します。

注意
私たちのコミュニティ メンバーの 1 人が、Crawlee Blog への寄稿としてこのブログを書きました。このようなブログを Crawlee Blog に投稿したい場合は、Discord チャンネルまでご連絡ください。

このチュートリアルが終わるまでに、LinkedIn から求人情報を取得するために使用できる、完全に機能する Web アプリケーションが完成します。

How to create a LinkedIn job scraper in Python with Crawlee

始めましょう。


前提条件

次のコマンドを使用して、新しい Crawlee for Python プロジェクトを作成することから始めましょう:

pipx run crawlee create linkedin-scraper

Crawlee が要求した場合は、ターミナルで PlaywrightCrawler を選択します。

インストール後、Crawlee for Python は定型コードを作成します。ディレクトリ (cd) をプロジェクト フォルダーに変更し、このコマンドを実行して依存関係をインストールできます。

poetry install

スクレイパーを構築できるように、Crawlee から提供されたファイルの編集を開始します。

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

GitHub でスターを付けてください ⭐️

Crawlee を使用して Python で LinkedIn ジョブ Scraper を構築する

このセクションでは、Crawlee for Python パッケージを使用してスクレイパーを構築します。 Crawlee について詳しくは、ドキュメントを参照してください。

1. LinkedIn 求人検索ページの検査

Web ブラウザで LinkedIn を開き、Web サイトからサインアウトします (アカウントがすでにログインしている場合)。次のようなインターフェイスが表示されるはずです。

How to create a LinkedIn job scraper in Python with Crawlee

求人セクションに移動し、希望の仕事と勤務地を検索して、URL をコピーします。

How to create a LinkedIn job scraper in Python with Crawlee

次のようなものになるはずです:

https://www.linkedin.com/jobs/search?keywords=バックエンド開発者&location=Canada&geoId=101174742&trk=public_jobs_jobs-search-bar_search-submit&position=1&pageNum=0

「?」の後の部分である検索パラメーターに焦点を当てます。私たちにとって、キーワードと場所のパラメーターが最も重要です。

ユーザーが指定した役職名はキーワード パラメーターに入力され、ユーザーが指定した場所は場所パラメーターに入力されます。最後に、geoId パラメータは削除されますが、他のパラメータは一定のままです。

main.py ファイルに変更を加えます。以下のコードをコピーして、main.py ファイルに貼り付けます。

from crawlee.playwright_crawler import PlaywrightCrawler
from .routes import router                                     
import urllib.parse

async def main(title: str, location: str, data_name: str) -> None:
    base_url = "https://www.linkedin.com/jobs/search"

    # URL encode the parameters
    params = {
        "keywords": title,
        "location": location,
        "trk": "public_jobs_jobs-search-bar_search-submit",
        "position": "1",
        "pageNum": "0"
    }

    encoded_params = urlencode(params)

    # Encode parameters into a query string
    query_string = '?' + encoded_params

    # Combine base URL with the encoded query string
    encoded_url = urljoin(base_url, "") + query_string

    # Initialize the crawler
    crawler = PlaywrightCrawler(
        request_handler=router,
    )

    # Run the crawler with the initial list of URLs
    await crawler.run([encoded_url])

    # Save the data in a CSV file
    output_file = f"{data_name}.csv"
    await crawler.export_data(output_file)

URL をエンコードしたので、次のステップは、生成されたルーターを調整して LinkedIn の求人情報を処理することです。

2. クローラーのルーティング

アプリケーションには 2 つのハンドラーを使用します。

  • デフォルトハンドラー

default_handler は開始 URL を処理します

  • 求人情報

job_listing ハンドラーは、個々のジョブの詳細を抽出します。

Playwright クローラーは、求人ページを巡回して、ページ上のすべての求人へのリンクを抽出します。

How to create a LinkedIn job scraper in Python with Crawlee

求人情報を調べると、求人情報のリンクがjobs-search__results-listというクラスの順序付きリスト内にあることがわかります。次に、Playwright ロケーター オブジェクトを使用してリンクを抽出し、処理のために job_listing ルートに追加します。

router = Router[PlaywrightCrawlingContext]()

@router.default_handler
async def default_handler(context: PlaywrightCrawlingContext) -> None:
    """Default request handler."""

    #select all the links for the job posting on the page
    hrefs = await context.page.locator('ul.jobs-search__results-list a').evaluate_all("links => links.map(link => link.href)")

    #add all the links to the job listing route
    await context.add_requests(
            [Request.from_url(rec, label='job_listing') for rec in hrefs]
        )

求人情報を取得したので、次のステップは詳細を収集することです。

各求人のタイトル、会社名、投稿時刻、求人投稿へのリンクを抽出します。開発ツールを開き、CSS セレクターを使用して各要素を抽出します。

How to create a LinkedIn job scraper in Python with Crawlee

各リストをスクレイピングした後、テキストから特殊文字を削除してクリーンにし、context.push_data 関数を使用してデータをローカル ストレージにプッシュします。

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

    await context.page.wait_for_load_state('load')

    job_title = await context.page.locator('div.top-card-layout__entity-info h1.top-card-layout__title').text_content()

    company_name  = await context.page.locator('span.topcard__flavor a').text_content()   

    time_of_posting= await context.page.locator('div.topcard__flavor-row span.posted-time-ago__text').text_content()


    await context.push_data(
        {
            # we are making use of regex to remove special characters for the extracted texts

            'title': re.sub(r'[\s\n]+', '', job_title),
            'Company name': re.sub(r'[\s\n]+', '', company_name),
            'Time of posting': re.sub(r'[\s\n]+', '', time_of_posting),
            'url': context.request.loaded_url,
        }
    )

3. Creating your application

For this project, we will be using Streamlit for the web application. Before we proceed, we are going to create a new file named app.py in your project directory. In addition, ensure you have Streamlit installed in your global Python environment before proceeding with this section.

import streamlit as st
import subprocess

# Streamlit form for inputs 
st.title("LinkedIn Job Scraper")

with st.form("scraper_form"):
    title = st.text_input("Job Title", value="backend developer")
    location = st.text_input("Job Location", value="newyork")
    data_name = st.text_input("Output File Name", value="backend_jobs")

    submit_button = st.form_submit_button("Run Scraper")

if submit_button:

    # Run the scraping script with the form inputs
    command = f"""poetry run python -m linkedin-scraper --title "{title}"  --location "{location}" --data_name "{data_name}" """

    with st.spinner("Crawling in progress..."):
         # Execute the command and display the results
        result = subprocess.run(command, shell=True, capture_output=True, text=True)

        st.write("Script Output:")
        st.text(result.stdout)

        if result.returncode == 0:
            st.success(f"Data successfully saved in {data_name}.csv")
        else:
            st.error(f"Error: {result.stderr}")

The Streamlit web application takes in the user's input and uses the Python Subprocess package to run the Crawlee scraping script.

4. Testing your app

Before we test the application, we need to make a little modification to the __main__ file in order for it to accommodate the command line arguments.

import asyncio
import argparse

from .main import main

def get_args():
    # ArgumentParser object to capture command-line arguments
    parser = argparse.ArgumentParser(description="Crawl LinkedIn job listings")


    # Define the arguments
    parser.add_argument("--title", type=str, required=True, help="Job title")
    parser.add_argument("--location", type=str, required=True, help="Job location")
    parser.add_argument("--data_name", type=str, required=True, help="Name for the output CSV file")


    # Parse the arguments
    return parser.parse_args()

if __name__ == '__main__':
    args = get_args()
    # Run the main function with the parsed command-line arguments
    asyncio.run(main(args.title, args.location, args.data_name))

We will start the Streamlit application by running this code in the terminal:

streamlit run app.py

This is what your application what the application should look like on the browser:

How to create a LinkedIn job scraper in Python with Crawlee

You will get this interface showing you that the scraping has been completed:

How to create a LinkedIn job scraper in Python with Crawlee

To access the scraped data, go over to your project directory and open the CSV file.

How to create a LinkedIn job scraper in Python with Crawlee

You should have something like this as the output of your CSV file.

Conclusion

In this tutorial, we have learned how to build an application that can scrape job posting data from LinkedIn using Crawlee. Have fun building great scraping applications with Crawlee.

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

Follow Crawlee for more content like this.

How to create a LinkedIn job scraper in Python with Crawlee

Crawlee

Crawlee is a web scraping and browser automation library. It helps you build reliable crawlers. Fast.

Thank you!

以上がCrawlee を使用して Python で LinkedIn ジョブ スクレーパーを作成する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
LinuxターミナルでPythonバージョンを表示するときに発生する権限の問題を解決する方法は?LinuxターミナルでPythonバージョンを表示するときに発生する権限の問題を解決する方法は?Apr 01, 2025 pm 05:09 PM

LinuxターミナルでPythonバージョンを表示する際の許可の問題の解決策PythonターミナルでPythonバージョンを表示しようとするとき、Pythonを入力してください...

HTMLを解析するために美しいスープを使用するにはどうすればよいですか?HTMLを解析するために美しいスープを使用するにはどうすればよいですか?Mar 10, 2025 pm 06:54 PM

この記事では、Pythonライブラリである美しいスープを使用してHTMLを解析する方法について説明します。 find()、find_all()、select()、およびget_text()などの一般的な方法は、データ抽出、多様なHTML構造とエラーの処理、および代替案(SEL

TensorflowまたはPytorchで深い学習を実行する方法は?TensorflowまたはPytorchで深い学習を実行する方法は?Mar 10, 2025 pm 06:52 PM

この記事では、深い学習のためにTensorflowとPytorchを比較しています。 関連する手順、データの準備、モデルの構築、トレーニング、評価、展開について詳しく説明しています。 特に計算グラップに関して、フレームワーク間の重要な違い

あるデータフレームの列全体を、Python内の異なる構造を持つ別のデータフレームに効率的にコピーする方法は?あるデータフレームの列全体を、Python内の異なる構造を持つ別のデータフレームに効率的にコピーする方法は?Apr 01, 2025 pm 11:15 PM

PythonのPandasライブラリを使用する場合、異なる構造を持つ2つのデータフレーム間で列全体をコピーする方法は一般的な問題です。 2つのデータがあるとします...

人気のあるPythonライブラリとその用途は何ですか?人気のあるPythonライブラリとその用途は何ですか?Mar 21, 2025 pm 06:46 PM

この記事では、numpy、pandas、matplotlib、scikit-learn、tensorflow、django、flask、and requestsなどの人気のあるPythonライブラリについて説明し、科学的コンピューティング、データ分析、視覚化、機械学習、Web開発、Hの使用について説明します。

Pythonでコマンドラインインターフェイス(CLI)を作成する方法は?Pythonでコマンドラインインターフェイス(CLI)を作成する方法は?Mar 10, 2025 pm 06:48 PM

この記事では、コマンドラインインターフェイス(CLI)の構築に関するPython開発者をガイドします。 Typer、Click、Argparseなどのライブラリを使用して、入力/出力の処理を強調し、CLIの使いやすさを改善するためのユーザーフレンドリーな設計パターンを促進することを詳述しています。

Pythonの仮想環境の目的を説明してください。Pythonの仮想環境の目的を説明してください。Mar 19, 2025 pm 02:27 PM

この記事では、Pythonにおける仮想環境の役割について説明し、プロジェクトの依存関係の管理と競合の回避に焦点を当てています。プロジェクト管理の改善と依存関係の問題を減らすための作成、アクティベーション、およびメリットを詳しく説明しています。

正規表現とは何ですか?正規表現とは何ですか?Mar 20, 2025 pm 06:25 PM

正規表現は、プログラミングにおけるパターンマッチングとテキスト操作のための強力なツールであり、さまざまなアプリケーションにわたるテキスト処理の効率を高めます。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

AI Hentai Generator

AI Hentai Generator

AIヘンタイを無料で生成します。

ホットツール

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

SublimeText3 中国語版

SublimeText3 中国語版

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

WebStorm Mac版

WebStorm Mac版

便利なJavaScript開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

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

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン