对求职者而言,挖掘机会、了解同行招聘动态是非常重要的。对于关注就业市场趋势的人群而言,Indeed 平台的职位列表搜索能提供关键参考。
在本文,我们会运用 Playwright 实现网页数据抓取,搭配 lxml 解析 HTML 内容,提取职位名称、招聘公司、工作地点、职位详情及发布链接等核心信息,最后将所有数据整理并保存到 CSV 文件中。
下面详细讲解一下步骤:
1.安装Python库和Playwright浏览器:
pip install playwright
pip install lxml
pip install pandas
playwright install
2.设置 Playwright 以进行网络刮擦:
Playwright 能够实现网页浏览器的自动化操作与交互。我们首先要配置 Playwright,以此启动 Chromium 浏览器、访问目标网页并提取页面内容。此外,通过 Playwright 还可以设置代理进行访问。
3.解析HTML内容:使用lxml解析,提取有用的数据。
Python
from lxml import html
def parse_job_listings_concise(content):
# 1. Parse the HTML and target all job listing items directly
tree = html.fromstring(content)
job_elements = tree.xpath('//ul[contains(@class, "jobsearch-ResultsList")]/li//a[contains(@class, "jcs-JobTitle")]')
# 2. Use list derivation to extract and assemble all data at once
jobs_data = [{
'Title': element.xpath('string(.)').strip(),
'Link': f"https://www.indeed.com{element.get('href')}",
'Company': element.xpath('string(./following::span[@data-testid="company-name"])').strip(),
'Location': element.xpath('string(./following::div[@data-testid="text-location"])').strip(),
'Description': ', '.join(p.text_content().strip() for p in element.xpath('./following::div[contains(@class, "job-snippet")]//li'))
} for element in job_elements]
return jobs_data
4.搜索想要获取的职位列表:使用get_page_content(url)抓取页面内容,parse_job_listings(content):使用 lxml 解析内容并提取任务数据。main():协调刮擦过程,获取数据并将其保存到 CSV 文件。
5.添加分页支持:调整页面需依靠 URL 中的查询参数 “start”:每当需要加载新页面时,“start” 参数的数值会按 10 的幅度递增。要增强爬虫从多页面收集数据的能力,您可以编写一个名为 scrape_multiple_pages 的函数。这个函数会通过逐次调整起始参数来修改基础 URL,进而访问后续各个页面。
6.自定义职位搜索查询:若想在数据抓取时精准定位特定职位名称或关键词,需在 Indeed 的 URL 中配置相应的查询搜索参数。借助这一自定义功能,抓取工具便能收集到特定职位或行业的相关数据。
代码示例:
Python
import pandas as pd
import asyncio
from playwright.async_api import async_playwright # Let's say you use Playwright
async def get_page_content(page, url):
await page.goto(url, wait_until="domcontentloaded")
return await page.content()
def parse_job_listings(content):
return [{'Title': 'Software Engineer', 'Company': 'Google'}]
async def main(url):
print(f"? Scraping data from {url}...")
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
# 1. Get content and parse data directly in one line
jobs_data = parse_job_listings(await get_page_content(page, url))
# 2. Convert data to DataFrame and save it directly
pd.DataFrame(jobs_data).to_csv('indeed_jobs.csv', index=False)
await browser.close()
print(f"✅ The data has been successfully saved to indeed_jobs.csv {len(jobs_data)} entries.")
if __name__ == "__main__":
target_url = 'https://www.indeed.com/q-usa-jobs.html'
asyncio.run(main(target_url))