介绍
在本文中,我们将构建一个 Web 应用程序,使用 Crawlee 和 Streamlit 抓取 LinkedIn 上的职位发布。
我们将使用 Crawlee for Python 在 Python 中创建 LinkedIn 职位抓取工具,从通过 Web 应用程序动态接收的用户输入中提取公司名称、职位名称、发布时间以及职位发布的链接。
注意
我们的一位社区成员撰写了此博客,作为对 Crawlee 博客的贡献。如果您想向 Crawlee 博客贡献此类博客,请通过我们的 Discord 频道与我们联系。
在本教程结束时,您将拥有一个功能齐全的 Web 应用程序,可用于从 LinkedIn 抓取职位发布。
我们开始吧。
先决条件
让我们首先使用以下命令创建一个新的 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 职位搜索页面
在网络浏览器中打开 LinkedIn 并从网站注销(如果您已经登录了帐户)。你应该看到这样的界面。
导航到职位部分,搜索您选择的职位和地点,然后复制 URL。
你应该有这样的东西:
https://www.linkedin.com/jobs/search?keywords=后端开发人员&location=加拿大&geoId=101174742&trk=public_jobs_jobs-search-bar_search-submit&position=1&pageNum=0
我们将重点关注搜索参数,即“?”后面的部分。关键字和位置参数对我们来说是最重要的。
用户提供的职位将被输入到keyword参数中,而用户提供的地点将被输入到location参数中。最后,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. 路由你的爬虫
我们将为您的应用程序使用两个处理程序:
- 默认处理程序
default_handler 处理起始 URL
- 职位列表
job_listing 处理程序提取各个作业的详细信息。
剧作家爬虫将爬行职位发布页面并提取页面上所有职位发布的链接。
当您检查职位发布时,您会发现职位发布链接位于一个名为 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

Python과 C는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1) Python은 간결한 구문 및 동적 타이핑으로 인해 빠른 개발 및 데이터 처리에 적합합니다. 2) C는 정적 타이핑 및 수동 메모리 관리로 인해 고성능 및 시스템 프로그래밍에 적합합니다.

Python 또는 C를 선택하는 것은 프로젝트 요구 사항에 따라 다릅니다. 1) 빠른 개발, 데이터 처리 및 프로토 타입 설계가 필요한 경우 Python을 선택하십시오. 2) 고성능, 낮은 대기 시간 및 근접 하드웨어 제어가 필요한 경우 C를 선택하십시오.

매일 2 시간의 파이썬 학습을 투자하면 프로그래밍 기술을 효과적으로 향상시킬 수 있습니다. 1. 새로운 지식 배우기 : 문서를 읽거나 자습서를 시청하십시오. 2. 연습 : 코드를 작성하고 완전한 연습을합니다. 3. 검토 : 배운 내용을 통합하십시오. 4. 프로젝트 실무 : 실제 프로젝트에서 배운 것을 적용하십시오. 이러한 구조화 된 학습 계획은 파이썬을 체계적으로 마스터하고 경력 목표를 달성하는 데 도움이 될 수 있습니다.

2 시간 이내에 Python을 효율적으로 학습하는 방법 : 1. 기본 지식을 검토하고 Python 설치 및 기본 구문에 익숙한 지 확인하십시오. 2. 변수, 목록, 기능 등과 같은 파이썬의 핵심 개념을 이해합니다. 3. 예제를 사용하여 마스터 기본 및 고급 사용; 4. 일반적인 오류 및 디버깅 기술을 배우십시오. 5. 목록 이해력 사용 및 PEP8 스타일 안내서와 같은 성능 최적화 및 모범 사례를 적용합니다.

Python은 초보자 및 데이터 과학에 적합하며 C는 시스템 프로그래밍 및 게임 개발에 적합합니다. 1. 파이썬은 간단하고 사용하기 쉽고 데이터 과학 및 웹 개발에 적합합니다. 2.C는 게임 개발 및 시스템 프로그래밍에 적합한 고성능 및 제어를 제공합니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

Python은 데이터 과학 및 빠른 개발에 더 적합한 반면 C는 고성능 및 시스템 프로그래밍에 더 적합합니다. 1. Python Syntax는 간결하고 학습하기 쉽고 데이터 처리 및 과학 컴퓨팅에 적합합니다. 2.C는 복잡한 구문을 가지고 있지만 성능이 뛰어나고 게임 개발 및 시스템 프로그래밍에 종종 사용됩니다.

파이썬을 배우기 위해 하루에 2 시간을 투자하는 것이 가능합니다. 1. 새로운 지식 배우기 : 목록 및 사전과 같은 1 시간 안에 새로운 개념을 배우십시오. 2. 연습 및 연습 : 1 시간을 사용하여 소규모 프로그램 작성과 같은 프로그래밍 연습을 수행하십시오. 합리적인 계획과 인내를 통해 짧은 시간에 Python의 핵심 개념을 마스터 할 수 있습니다.

Python은 배우고 사용하기 쉽고 C는 더 강력하지만 복잡합니다. 1. Python Syntax는 간결하며 초보자에게 적합합니다. 동적 타이핑 및 자동 메모리 관리를 사용하면 사용하기 쉽지만 런타임 오류가 발생할 수 있습니다. 2.C는 고성능 응용 프로그램에 적합한 저수준 제어 및 고급 기능을 제공하지만 학습 임계 값이 높고 수동 메모리 및 유형 안전 관리가 필요합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

SublimeText3 영어 버전
권장 사항: Win 버전, 코드 프롬프트 지원!

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

WebStorm Mac 버전
유용한 JavaScript 개발 도구

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.
