導入
この記事では、Crawlee と Streamlit を使用して、LinkedIn をスクレイピングして求人情報を取得する Web アプリケーションを構築します。
Crawlee for Python を使用して、Python で LinkedIn 求人スクレーパーを作成し、Web アプリケーションを通じて動的に受信したユーザー入力から会社名、役職、投稿時刻、求人情報へのリンクを抽出します。
注意
私たちのコミュニティ メンバーの 1 人が、Crawlee Blog への寄稿としてこのブログを書きました。このようなブログを Crawlee Blog に投稿したい場合は、Discord チャンネルまでご連絡ください。
このチュートリアルが終わるまでに、LinkedIn から求人情報を取得するために使用できる、完全に機能する Web アプリケーションが完成します。
始めましょう。
前提条件
次のコマンドを使用して、新しい 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 サイトからサインアウトします (アカウントがすでにログインしている場合)。次のようなインターフェイスが表示されるはずです。
求人セクションに移動し、希望の仕事と勤務地を検索して、URL をコピーします。
次のようなものになるはずです:
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 クローラーは、求人ページを巡回して、ページ上のすべての求人へのリンクを抽出します。
求人情報を調べると、求人情報のリンクが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 セレクターを使用して各要素を抽出します。
各リストをスクレイピングした後、テキストから特殊文字を削除してクリーンにし、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:
You will get this interface showing you that the scraping has been completed:
To access the scraped data, go over to your project directory and open the CSV file.
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.

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

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

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

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

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

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

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

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

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


ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

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

人気の記事

ホットツール

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

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

WebStorm Mac版
便利なJavaScript開発ツール

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

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

ホットトピック



