以采集某招聘网站职位列表为例,典型流程如下:
import requests
from bs4 import BeautifulSoup
import csv
url = "https://example.com/jobs?page=1"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
jobs = soup.select('.job-item')
with open('jobs.csv', 'w', newline='', encoding='utf-8-sig') as f:
writer = csv.writer(f)
writer.writerow(['职位', '公司', '薪资', '城市'])
for job in jobs:
title = job.select_one('.job-title').text.strip()
company = job.select_one('.company-name').text.strip()
salary = job.select_one('.salary').text.strip()
location = job.select_one('.location').text.strip()
writer.writerow([title, company, salary, location])
上述代码展示了基础爬虫的完整骨架,但实际应用中还需处理异常(如网络超时、解析失败)、去重(避免重复采集同一URL)、重试(针对临时性错误)等机制。例如,可通过functools.retry库实现自动重试,或用Redis记录已访问URL集合防止重复请求。
Python生态中,爬虫相关工具库分工明确,组合使用可覆盖90%以上场景。以下按功能模块分类说明:
requests库以简洁API著称,支持会话保持(Session)、代理设置、证书验证等功能。关键特性如下:
proxies = {
"http": "http://127.0.0.1:8080",
"https": "http://127.0.0.1:8080"
}
response = requests.get(url, headers=headers, proxies=proxies, timeout=10)
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
session = requests.Session()
retries = Retry(total=3, backoff_factor=0.5, status_forcelist=[500,502,503,504])
session.mount('http://', HTTPAdapter(max_retries=retries))
session.mount('https://', HTTPAdapter(max_retries=retries))
BeautifulSoup支持HTML/XML解析,提供CSS选择器与标签遍历两种方式。其优势在于:
典型应用场景:从新闻列表页提取标题与链接:
titles = soup.select('h2 a')
for t in titles:
print(t.get_text(strip=True), '→', t['href'])
注意:当页面内容由JavaScript动态加载时(如分页按钮需点击后才显示),BeautifulSoup无法直接获取,需结合Selenium或分析XHR请求。
Selenium通过驱动浏览器(Chrome/Firefox)实现动态页面渲染,适用于以下场景:
关键操作示例:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://example.com/login")
driver.find_element(By.ID, "username").send_keys("user")
driver.find_element(By.ID, "password").send_keys("pass")
driver.find_element(By.CSS_SELECTOR, ".login-btn").click()
# 等待登录后页面加载完成
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, "user-info"))
)
html = driver.page_source
driver.quit()
缺点:资源消耗大、速度慢,需配合隐式等待与显式等待避免元素未加载完成。生产环境建议用Playwright替代(支持无头模式更稳定)。
Scrapy是异步非阻塞框架,适合大规模数据采集。其核心组件包括:
典型爬虫文件结构:
import scrapy
class JobSpider(scrapy.Spider):
name = "jobs"
start_urls = ["https://example.com/jobs?page=1"]
def parse(self, response):
for job in response.css('.job-item'):
yield {
'title': job.css('.job-title::text').get(),
'company': job.css('.company-name::text').get()
}
# 翻页逻辑
next_page = response.css('.next-page::attr(href)').get()
if next_page:
yield response.follow(next_page, callback=self.parse)
运行命令:scrapy crawl jobs -o jobs.json
优势:内置中间件、自动限速、日志系统;劣势:学习曲线陡峭,适合中大型项目。
网站为保护数据资源,常部署反爬措施。常见类型与应对方案如下:
通过User-Agent、IP、Cookie识别异常行为。解决方案:
部分数据通过AJAX请求加载,需直接抓取API接口。步骤:
示例:某网站分页数据实际请求为:https://api.example.com/jobs?keyword=python&page=2
则无需解析前端HTML,直接请求该API返回JSON数据。
常见于登录环节,需模拟拖动轨迹。高级方案:
# 模拟拖动示例(简化版)
action = ActionChains(driver)
action.click_and_hold(slider).perform()
for i in range(5):
action.move_by_offset(20, 0).perform()
time.sleep(0.1)
action.release().perform()
部分请求携带加密参数(如sign、token),需逆向JS代码。方法:
注意:逆向行为需遵守网站Robots协议,仅用于合法场景。
根据《网络安全法》第27条及《民法典》第1034条,爬虫开发者需关注以下红线:
“任何个人和组织不得从事非法侵入他人网络、干扰网络正常功能及其防护措施的活动。”
具体合规要点:
https://目标网站/robots.txt,确认目标路径未被禁止。例如:User-agent: *
Disallow: /admin/
Disallow: /search?q=典型案例参考:
以下以采集“拉勾网Python岗位数据”为例,演示完整流程(仅作教学用途,实际使用需遵守其Robots协议):
目标字段:职位名称、公司名称、薪资范围、工作年限要求、学历要求、城市、发布日期
采用requests + BeautifulSoup + SQLite方案,兼顾易用性与可扩展性
import requests
from bs4 import BeautifulSoup
import sqlite3
import time
import random
# 创建数据库表
conn = sqlite3.connect('jobs.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS jobs
(id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT, company TEXT, salary TEXT, experience TEXT,
education TEXT, city TEXT, date TEXT)''')
# 采集10页数据
for page in range(1, 11):
url = f"https://www.lagou.com/zhaopin/Python/{page}/"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)...",
"Referer": "https://www.lagou.com/"
}
response = requests.get(url, headers=headers)
# 检查响应状态
if response.status_code != 200:
print(f"第{page}页请求失败,状态码:{response.status_code}")
continue
soup = BeautifulSoup(response.text, 'html.parser')
jobs = soup.select('.s_position_list .item_con_list li')
for job in jobs:
title = job.select_one('.p_top h3').text.strip()
company = job.select_one('.company_name a').text.strip()
salary = job.select_one('.money').text.strip()
# 补充字段提取逻辑...
cursor.execute("INSERT INTO jobs VALUES (NULL,?,?,?,?,?,?,?)",
(title, company, salary, "1-3年", "本科", "北京", "2023-10-20"))
conn.commit()
print(f"第{page}页采集完成")
time.sleep(random.uniform(2, 4)) # 随机休眠
conn.close()
去重(相同职位重复采集)、异常值处理(如薪资“面议”转为区间)、格式统一(“1-3年”→“1~3年”)
A:可能原因:① 页面内容由JS动态加载;② 请求头缺失关键字段(如Referer);③ IP被封禁。解决步骤:① 检查Network面板是否找到XHR请求;② 用浏览器开发者工具复制完整请求头;③ 更换IP或降低频率。
A:常见分页模式:
• URL参数分页(?page=1,2,3...)→ 循环生成URL
• 滚动加载(向下滚动自动加载)→ 用Selenium模拟滚动
• 加载更多按钮 → 点击按钮并等待新内容加载
A:方案:
• 用Linux cron定时任务(如每天凌晨执行)
• 用Supervisor管理进程
• 部署到云服务器(如阿里云ECS)
• 使用Scrapy + Scrapyd + Flower监控系统
A:策略:
• 控制请求频率(≥3秒/次)
• 使用代理IP池(至少100个IP轮换)
• 模拟真实浏览器行为(随机User-Agent、添加Cookie)
• 避免并发过高(Scrapy中CONCURRENT_REQUESTS≤16)
在基础之上,可进一步提升效率: