🐍 Python Day80:Selenium 进阶 — 无头模式、反检测与数据采集
🕐 预计用时:3-4 小时 | 🎯 目标:掌握无头模式、反检测技巧、滚动加载、批量数据采集
📖 今日目录
- Selenium + BeautifulSoup 组合
1. 无头模式
无头模式(Headless)= 后台运行浏览器,不显示界面。适合服务器环境和批量采集。
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# === 方式1:Chrome 无头模式 ===
options = Options()
options.add_argument('--headless=new') # 新版无头模式(推荐)
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--window-size=1920,1080')
driver = webdriver.Chrome(options=options)
driver.get('https://www.baidu.com')
print(f'标题: {driver.title}')
# 截图(无头模式也能截图!)
driver.save_screenshot('headless_screenshot.png')
# 获取页面源码
html = driver.page_source
driver.quit()
# === 方式2:Firefox 无头模式 ===
from selenium.webdriver.firefox.options import Options as FirefoxOptions
options = FirefoxOptions()
options.add_argument('--headless')
# driver = webdriver.Firefox(options=options)
# === 方式3:Edge 无头模式 ===
from selenium.webdriver.edge.options import Options as EdgeOptions
options = EdgeOptions()
options.add_argument('--headless=new')
# driver = webdriver.Edge(options=options)
💡 无头模式 vs 有头模式:
• 有头模式:能看到浏览器窗口,调试方便,适合开发阶段
• 无头模式:不显示界面,速度快 30-50%,内存省 50%,适合生产环境
开发调试时用有头模式,确认没问题后切换到无头模式。
2. 反检测技巧
很多网站会检测是否是自动化浏览器。以下技巧可以绕过常见检测。
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
# === 技巧1:修改 User-Agent ===
options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
'AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/120.0.0.0 Safari/537.36')
# === 技巧2:禁用自动化标志 ===
options.add_argument('--disable-blink-features=AutomationControlled')
options.add_experimental_option('excludeSwitches', ['enable-automation'])
options.add_experimental_option('useAutomationExtension', False)
# === 技巧3:禁用 WebDriver 检测 ===
driver = webdriver.Chrome(options=options)
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
'source': '''
// 隐藏 webdriver 属性
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined
});
// 伪造 plugins
Object.defineProperty(navigator, 'plugins', {
get: () => [1, 2, 3, 4, 5]
});
// 伪造 languages
Object.defineProperty(navigator, 'languages', {
get: () => ['zh-CN', 'zh', 'en']
});
// 隐藏 Chrome 自动化标志
window.chrome = { runtime: {} };
'''
})
# === 技巧4:使用 undetected-chromedriver(推荐!最强反检测)===
# pip install undetected-chromedriver
import undetected_chromedriver as uc
driver = uc.Chrome() # 一行搞定所有反检测!
driver.get('https://nowsecure.nl') # 反检测测试网站
driver.save_screenshot('undetected.png')
driver.quit()
# === 技巧5:随机化操作间隔(模拟人类)===
import time
import random
def human_delay(min_sec=1, max_sec=3):
"""模拟人类操作间隔"""
time.sleep(random.uniform(min_sec, max_sec))
# 使用
driver.get('https://example.com')
human_delay(2, 4) # 随机等 2-4 秒
driver.find_element('id', 'btn').click()
human_delay(1, 3) # 随机等 1-3 秒
📋 反检测策略总结
3. 滚动加载处理
很多网站使用"无限滚动"——滚到底部才加载更多内容。需要代码模拟滚动。
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('https://example.com/infinite-scroll')
# === 方法1:滚动到指定位置 ===
driver.execute_script("window.scrollTo(0, 500);") # 滚动到 500px
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") # 滚动到底部
# === 方法2:滚动到指定元素 ===
element = driver.find_element(By.ID, 'target')
driver.execute_script("arguments[0].scrollIntoView(true);", element)
# === 方法3:无限滚动——反复滚到底部直到没有新内容 ===
def scroll_to_bottom(driver, max_scrolls=20, wait_time=2):
"""滚动到底部,等待加载,重复直到没有新内容"""
last_height = driver.execute_script("return document.body.scrollHeight")
scroll_count = 0
while scroll_count < max_scrolls:
# 滚动到底部
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# 等待新内容加载
time.sleep(wait_time)
# 计算新的滚动高度
new_height = driver.execute_script("return document.body.scrollHeight")
# 如果高度没变,说明已经到底
if new_height == last_height:
print(f'✅ 已到底部,共滚动 {scroll_count} 次')
break
last_height = new_height
scroll_count += 1
print(f'📜 第 {scroll_count} 次滚动,页面高度: {new_height}px')
return scroll_count
# 使用
scroll_count = scroll_to_bottom(driver, max_scrolls=50, wait_time=1.5)
print(f'共滚动 {scroll_count} 次')
# 然后提取所有数据
items = driver.find_elements(By.CSS_SELECTOR, '.item')
print(f'共找到 {len(items)} 个元素')
driver.quit()
# === 方法4:滚动指定容器(如弹窗内的列表)===
def scroll_container(driver, container_selector, max_scrolls=20):
"""滚动指定容器"""
container = driver.find_element(By.CSS_SELECTOR, container_selector)
for i in range(max_scrolls):
# 获取容器当前滚动位置
last_scroll = driver.execute_script(
"return arguments[0].scrollTop", container
)
# 向下滚动
driver.execute_script(
"arguments[0].scrollTop += 500", container
)
time.sleep(1)
# 检查是否到底
new_scroll = driver.execute_script(
"return arguments[0].scrollTop", container
)
if new_scroll == last_scroll:
break
# 使用
scroll_container(driver, '.modal-body', max_scrolls=10)
4. 实战:采集动态页面数据
"""
实战:从动态加载的网站采集商品数据
场景:网站使用 JavaScript 渲染,requests 无法获取数据
"""
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
import pandas as pd
import time
import random
def scrape_products(url, max_pages=5):
"""采集商品列表数据"""
options = webdriver.ChromeOptions()
options.add_argument('--headless=new')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64)')
driver = webdriver.Chrome(options=options)
wait = WebDriverWait(driver, 15)
all_products = []
try:
for page in range(1, max_pages + 1):
print(f'\n📄 正在采集第 {page} 页...')
# 打开页面
page_url = f'{url}?page={page}'
driver.get(page_url)
# 等待商品列表加载
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.product-card')))
# 模拟人类延迟
time.sleep(random.uniform(1, 2))
# 提取商品信息
products = driver.find_elements(By.CSS_SELECTOR, '.product-card')
for product in products:
try:
name = product.find_element(By.CSS_SELECTOR, '.title').text
price = product.find_element(By.CSS_SELECTOR, '.price').text
sales = product.find_element(By.CSS_SELECTOR, '.sales').text
shop = product.find_element(By.CSS_SELECTOR, '.shop').text
all_products.append({
'名称': name,
'价格': price,
'销量': sales,
'店铺': shop,
'页码': page,
})
except Exception as e:
print(f' ⚠️ 跳过一个商品: {e}')
continue
print(f' ✅ 采集到 {len(products)} 个商品')
# 检查是否有下一页
try:
next_btn = driver.find_element(By.CSS_SELECTOR, '.next-page')
if 'disabled' in next_btn.get_attribute('class'):
print(' ℹ️ 已是最后一页')
break
except:
print(' ℹ️ 没有下一页按钮')
break
# 随机延迟
time.sleep(random.uniform(2, 4))
except Exception as e:
print(f'❌ 采集出错: {e}')
driver.save_screenshot('error.png')
finally:
driver.quit()
# 保存数据
if all_products:
df = pd.DataFrame(all_products)
df.to_csv('products.csv', index=False, encoding='utf-8-sig')
print(f'\n✅ 采集完成!共 {len(all_products)} 个商品,已保存到 products.csv')
return all_products
# 执行采集
# products = scrape_products('https://example.com/products', max_pages=10)
5. 实战:自动翻页采集
"""
实战:翻页采集 + 断点续传
如果中途中断,下次可以从上次停止的地方继续
"""
import json
import os
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
import time
# 断点文件
CHECKPOINT_FILE = 'scrape_checkpoint.json'
def load_checkpoint():
"""加载断点"""
if os.path.exists(CHECKPOINT_FILE):
with open(CHECKPOINT_FILE, 'r') as f:
return json.load(f)
return {'last_page': 0, 'total_items': 0}
def save_checkpoint(page, total):
"""保存断点"""
with open(CHECKPOINT_FILE, 'w') as f:
json.dump({'last_page': page, 'total_items': total}, f)
def scrape_with_checkpoint(base_url, max_pages=100):
"""带断点续传的采集"""
checkpoint = load_checkpoint()
start_page = checkpoint['last_page'] + 1
total_items = checkpoint['total_items']
print(f'📍 从第 {start_page} 页开始,已采集 {total_items} 条')
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 15)
all_data = []
try:
for page in range(start_page, max_pages + 1):
print(f'📄 第 {page} 页...', end=' ')
driver.get(f'{base_url}?page={page}')
# 等待加载
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.item')))
time.sleep(1.5)
# 提取数据
items = driver.find_elements(By.CSS_SELECTOR, '.item')
for item in items:
data = {
'title': item.find_element(By.CSS_SELECTOR, '.title').text,
'price': item.find_element(By.CSS_SELECTOR, '.price').text,
}
all_data.append(data)
total_items += len(items)
print(f'✅ {len(items)} 条,累计 {total_items} 条')
# 每 10 页保存一次断点
if page % 10 == 0:
save_checkpoint(page, total_items)
print(f' 💾 断点已保存 (第 {page} 页)')
# 检查是否到底
try:
next_btn = driver.find_element(By.CSS_SELECTOR, '.next.disabled')
print(' ℹ️ 已到最后一页')
break
except:
pass
time.sleep(2)
except KeyboardInterrupt:
print(f'\n⚠️ 手动中断!正在保存断点...')
except Exception as e:
print(f'\n❌ 出错: {e}')
finally:
# 保存断点和数据
save_checkpoint(page if 'page' in dir() else start_page, total_items)
driver.quit()
# 保存数据
if all_data:
import pandas as pd
df = pd.DataFrame(all_data)
df.to_csv('scraped_data.csv', index=False, encoding='utf-8-sig')
print(f'\n✅ 共采集 {total_items} 条数据')
return all_data
6. 实战:截图生成报告
"""
实战:自动截图生成网页快照报告
"""
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
from datetime import datetime
import os
import time
def capture_webpage_report(urls, output_dir='screenshots'):
"""批量截图生成报告"""
os.makedirs(output_dir, exist_ok=True)
options = webdriver.ChromeOptions()
options.add_argument('--headless=new')
options.add_argument('--no-sandbox')
options.add_argument('--window-size=1920,1080')
driver = webdriver.Chrome(options=options)
wait = WebDriverWait(driver, 15)
results = []
for i, url in enumerate(urls, 1):
print(f'📸 [{i}/{len(urls)}] {url}')
try:
driver.get(url)
wait.until(EC.presence_of_element_located((By.TAG_NAME, 'body')))
time.sleep(2) # 等待页面完全渲染
# 截图
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
filename = f'{output_dir}/page_{i}_{timestamp}.png'
driver.save_screenshot(filename)
# 获取页面信息
title = driver.title
page_height = driver.execute_script("return document.body.scrollHeight")
load_time = driver.execute_script(
"return performance.timing.loadEventEnd - performance.timing.navigationStart"
)
results.append({
'url': url,
'title': title,
'screenshot': filename,
'page_height': page_height,
'load_time_ms': load_time,
})
print(f' ✅ {title} ({page_height}px, {load_time}ms)')
except Exception as e:
print(f' ❌ 失败: {e}')
results.append({'url': url, 'error': str(e)})
driver.quit()
# 生成 HTML 报告
html = ''
html += '📸 网页快照报告
'
html += f'生成时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
'
for r in results:
html += '
'
if 'error' in r:
html += f'❌ {r["url"]}
错误: {r["error"]}
'
else:
html += f'✅ {r["title"]}
'
html += f'URL: {r["url"]}
'
html += f'页面高度: {r["page_height"]}px | 加载时间: {r["load_time_ms"]}ms
'
html += f''
html += ''
report_file = f'{output_dir}/report.html'
with open(report_file, 'w', encoding='utf-8') as f:
f.write(html)
print(f'\n✅ 报告已生成: {report_file}')
return results
# 使用
# capture_webpage_report([
# 'https://www.baidu.com',
# 'https://www.python.org',
# 'https://github.com',
# ])
7. Selenium + BeautifulSoup 组合
"""
最佳组合:Selenium 负责获取页面,BeautifulSoup 负责解析数据
各取所长,效率最高!
"""
from selenium import webdriver
from bs4 import BeautifulSoup
import time
def scrape_with_selenium_and_bs4(url):
"""Selenium 获取 + BS4 解析"""
# 1. Selenium 获取渲染后的 HTML
driver = webdriver.Chrome()
driver.get(url)
time.sleep(3) # 等待 JS 渲染
# 滚动加载更多内容
for _ in range(5):
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(1)
# 获取完整 HTML(含 JS 渲染后的内容)
html = driver.page_source
driver.quit()
# 2. BeautifulSoup 解析 HTML(比 Selenium find_element 快 10 倍!)
soup = BeautifulSoup(html, 'html.parser')
# 3. 提取数据
products = []
for card in soup.select('.product-card'):
product = {
'名称': card.select_one('.title').get_text(strip=True) if card.select_one('.title') else '',
'价格': card.select_one('.price').get_text(strip=True) if card.select_one('.price') else '',
'销量': card.select_one('.sales').get_text(strip=True) if card.select_one('.sales') else '',
'评分': card.select_one('.rating').get_text(strip=True) if card.select_one('.rating') else '',
}
products.append(product)
return products
# 为什么用组合?
# Selenium find_element: 每次调用都查询 DOM,慢
# BS4 select: 一次性解析整个 HTML,快
# 先用 Selenium 拿到完整 HTML,再用 BS4 批量解析 → 效率最优
💡 Selenium vs requests + BS4 选择指南:
• 静态页面(服务器直接返回 HTML)→ requests + BeautifulSoup
• 动态页面(JS 渲染后才有数据)→ Selenium + BeautifulSoup
• 需要交互(点击、登录、表单)→ Selenium
• API 接口(返回 JSON)→ requests(最简单!)
原则:能用 requests 就不用 Selenium,能用 BS4 就不用 Selenium find_element。
8. 性能优化
# === 优化1:禁用图片加载(提速 50%)===
options = webdriver.ChromeOptions()
prefs = {
'profile.managed_default_content_settings.images': 2, # 禁用图片
# 下面两项可能影响页面布局,仅在采集不需要样式的纯文本时启用
'profile.managed_default_content_settings.stylesheets': 2, # 禁用 CSS
'profile.managed_default_content_settings.fonts': 2, # 禁用字体
}
options.add_experimental_option('prefs', prefs)
# === 优化2:复用浏览器实例(避免反复启动)===
class BrowserPool:
"""浏览器连接池"""
def __init__(self, max_size=3):
self.max_size = max_size
self.drivers = []
def get_driver(self):
if self.drivers:
return self.drivers.pop()
return webdriver.Chrome()
def return_driver(self, driver):
if len(self.drivers) < self.max_size:
# 清理状态
driver.delete_all_cookies()
self.drivers.append(driver)
else:
driver.quit()
def close_all(self):
for d in self.drivers:
d.quit()
self.drivers.clear()
# === 优化3:并行采集(多线程)===
from concurrent.futures import ThreadPoolExecutor
import threading
def scrape_url(url):
"""采集单个 URL(每个线程独立的 driver)"""
driver = webdriver.Chrome()
driver.get(url)
title = driver.title
driver.quit()
return {'url': url, 'title': title}
urls = [
'https://www.baidu.com',
'https://www.python.org',
'https://github.com',
]
# 3 个线程并行采集
with ThreadPoolExecutor(max_workers=3) as executor:
results = list(executor.map(scrape_url, urls))
for r in results:
print(f'{r["url"]} → {r["title"]}')
# === 优化4:只等需要的元素 ===
# 不要等整个页面加载完成
options.page_load_strategy = 'eager' # DOM 就绪就继续,不等图片等资源
9. 今日练习
🏋️ 练习 1:无头模式采集
# 用无头模式打开 python.org
# 截图并获取页面标题和所有链接
# 对比有头和无头模式的速度差异
🏋️ 练习 2:无限滚动采集
# 找一个使用无限滚动的网站(如微博、Twitter)
# 实现自动滚动 + 数据采集
# 统计共加载了多少条数据
🏋️ 练习 3:Selenium + BS4 组合
# 采集一个动态网站的商品列表:
# 1. Selenium 获取渲染后的 HTML
# 2. BS4 解析提取数据
# 3. 保存为 CSV
# 4. 对比 Selenium find_element 和 BS4 select 的速度
10. 今日小结
| |
|---|
| --headless=new |
| 禁用 AutomationControlled / CDP 命令 / undetected-chromedriver |
| scrollTo(0, scrollHeight) |
| |
| |
| Selenium 获取页面 + BS4 解析数据(各取所长) |
| 禁用图片 / 复用浏览器 / 并行采集 / eager 加载策略 |
🎉 Selenium 阶段完结!
Day 79-80 你掌握了浏览器自动化的核心技能:
✅ 元素定位 · 操作模拟 · 等待策略 · 弹窗/iframe 处理
✅ 无头模式 · 反检测 · 滚动加载 · 数据采集 · 性能优化
接下来进入 openpyxl 操作 Excel(Day 81)—— 用 Python 自动处理 Excel 报表!