検索
ホームページバックエンド開発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 までご連絡ください。
リストと配列の選択は、大規模なデータセットを扱うPythonアプリケーションの全体的なパフォーマンスにどのように影響しますか?リストと配列の選択は、大規模なデータセットを扱うPythonアプリケーションの全体的なパフォーマンスにどのように影響しますか?May 03, 2025 am 12:11 AM

forhandlinglaredataSetsinpython、usenumpyArrays forbetterperformance.1)numpyarraysarememory-effictientandfasterfornumericaloperations.2)nusinnnnedarytypeconversions.3)レバレッジベクトル化は、測定済みのマネージメーシェイメージーウェイズデイタイです

Pythonのリストと配列にメモリがどのように割り当てられるかを説明します。Pythonのリストと配列にメモリがどのように割り当てられるかを説明します。May 03, 2025 am 12:10 AM

inpython、listsusedynamicmemoryallocation with allocation、whilenumpyArraysalocatefixedmemory.1)listsallocatemorememorythanneededededinitivative.2)numpyArrayasallocateexactmemoryforements、rededicablebutlessflexibilityを提供します。

Pythonアレイ内の要素のデータ型をどのように指定しますか?Pythonアレイ内の要素のデータ型をどのように指定しますか?May 03, 2025 am 12:06 AM

inpython、youcanspecthedatatypeyfelemeremodelernspant.1)usenpynernrump.1)usenpynerp.dloatp.ploatm64、フォーマーpreciscontrolatatypes。

Numpyとは何ですか、そしてなぜPythonの数値コンピューティングにとって重要なのですか?Numpyとは何ですか、そしてなぜPythonの数値コンピューティングにとって重要なのですか?May 03, 2025 am 12:03 AM

numpyisessentialfornumericalcomputinginpythonduetoitsspeed、memory efficiency、andcomprehensivematicalfunctions.1)それは、performsoperations.2)numpyArraysaremoremory-efficientthanpythonlists.3)Itofderangeofmathematicaloperty

「隣接するメモリ割り当て」の概念と、配列にとってその重要性について説明します。「隣接するメモリ割り当て」の概念と、配列にとってその重要性について説明します。May 03, 2025 am 12:01 AM

contiguousMemoryAllocationisucial forArraysは、ForeffienceAndfastelementAccess.1)iteenablesConstantTimeAccess、O(1)、DuetodirectAddresscalculation.2)itemprovesefficiencyByAllowingMultiblementFechesperCacheLine.3)itimplifieMememm

Pythonリストをどのようにスライスしますか?Pythonリストをどのようにスライスしますか?May 02, 2025 am 12:14 AM

slicingapythonlistisdoneusingtheyntaxlist [start:stop:step] .hore'showitworks:1)startisthe indexofthefirstelementtoinclude.2)spotisthe indexofthefirmenttoeexclude.3)staptistheincrementbetbetinelements

Numpyアレイで実行できる一般的な操作は何ですか?Numpyアレイで実行できる一般的な操作は何ですか?May 02, 2025 am 12:09 AM

numpyallows forvariousoperationsonarrays:1)basicarithmeticlikeaddition、減算、乗算、および分割; 2)AdvancedperationssuchasmatrixMultiplication;

Pythonを使用したデータ分析では、配列はどのように使用されていますか?Pythonを使用したデータ分析では、配列はどのように使用されていますか?May 02, 2025 am 12:09 AM

Arraysinpython、特にnumpyandpandas、aresentialfordataanalysis、offeringspeedandeficiency.1)numpyarraysenable numpyarraysenable handling forlaredatasents andcomplexoperationslikemoverages.2)Pandasextendsnumpy'scapabivitieswithdataframesfortruc

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衣類リムーバー

Video Face Swap

Video Face Swap

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

ホットツール

Dreamweaver Mac版

Dreamweaver Mac版

ビジュアル Web 開発ツール

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

このプロジェクトは osdn.net/projects/mingw に移行中です。引き続きそこでフォローしていただけます。 MinGW: GNU Compiler Collection (GCC) のネイティブ Windows ポートであり、ネイティブ Windows アプリケーションを構築するための自由に配布可能なインポート ライブラリとヘッダー ファイルであり、C99 機能をサポートする MSVC ランタイムの拡張機能が含まれています。すべての MinGW ソフトウェアは 64 ビット Windows プラットフォームで実行できます。

PhpStorm Mac バージョン

PhpStorm Mac バージョン

最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

SublimeText3 英語版

SublimeText3 英語版

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。