使用Python抓取职位信息通常涉及以下步骤:
确定目标网站
选择你想抓取职位信息的招聘网站。
分析目标网站
观察网站构造和源码,确定职位信息的位置和类型。
发送HTTP请求
使用`requests`库发送HTTP请求获取页面信息。
解析页面
使用`BeautifulSoup`或其他解析工具(如正则表达式)解析网页内容。
提取信息
从网页中提取所需的职位信息、公司信息及它们的URL等相关信息。
存储信息
将提取到的职位信息存储在数据库或文件中。
处理反爬
分析网站的反爬机制并采取相应策略避免被反爬。
import requests
from bs4 import BeautifulSoup
import json
import time
def get_positions(page_number):
url = f"https://www.51job.com/list-{page_number}.html"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'lxml')
positions = soup.find_all('div', class_='el dw_table')
result = []
for position in positions:
title = position.find('a', class_='t1').text
company = position.find('a', class_='t2').text
location = position.find('span', class_='t3').text
salary = position.find('span', class_='t4').text
date = position.find('span', class_='t5').text
result.append({
'title': title,
'company': company,
'location': location,
'salary': salary,
'date': date
})
return result
positions = []
for i in range(1, 11): 假设我们想要抓取前10页的数据
print(f"Scraping page {i}...")
page_positions = get_positions(i)
positions.extend(page_positions)
time.sleep(1) 暂停1秒,模拟人类行为避免被网站封禁
将抓取到的职位信息保存到文件中
with open('positions.json', 'w', encoding='utf-8') as f:
json.dump(positions, f, ensure_ascii=False, indent=4)
请注意,抓取网站数据时应遵守网站的`robots.txt`文件规定,并尊重网站的使用条款。此外,频繁的请求可能会对网站服务器造成负担,因此请合理安排抓取频率。