浏
浏览器自动化指南
作者:鹿Sir开发工具v1
浏览器自动化操作指南,指导使用Playwright/Puppeteer/CDP协议实现网页自动化,包括表单填写、数据抓取、截图、页面交互、多标签管理等。当用户需要自动化操作浏览器、网页数据抓取、自动填表、批量截图、网页测试自动化时触发。触发词:浏览器自动化、网页抓取、自动填表、Playwright、Puppeteer、网页截图、自动化测试、爬虫。
下载量
251
点赞
63
价格
免费
技能文档
---
name: liulanqi-zidonghua-zhinan
title: 浏览器自动化指南
category: 开发工具
description: 浏览器自动化操作指南,指导使用Playwright/Puppeteer/CDP协议实现网页自动化,包括表单填写、数据抓取、截图、页面交互、多标签管理等。当用户需要自动化操作浏览器、网页数据抓取、自动填表、批量截图、网页测试自动化时触发。触发词:浏览器自动化、网页抓取、自动填表、Playwright、Puppeteer、网页截图、自动化测试、爬虫。
---
# 浏览器自动化操作指南
## 核心能力
指导使用现代浏览器自动化工具实现网页操作自动化,覆盖页面导航、元素交互、数据提取、截图、文件下载等场景。
## 工具选择
| 工具 | 适用场景 | 语言 | 特点 |
|------|---------|------|------|
| Playwright | 通用自动化 | Python/Node | 多浏览器支持,API现代 |
| Puppeteer | Chrome自动化 | Node | Chrome原生,社区大 |
| Selenium | 企业级测试 | 多语言 | 兼容性最广 |
| CDP直连 | 底层控制 | 任意 | 最灵活,需理解协议 |
**默认推荐**:Playwright(Python版),API简洁且功能完整。
## 环境准备
### Playwright (Python)
```bash
pip install playwright
playwright install chromium
```
### Playwright (Node.js)
```bash
npm install playwright
npx playwright install chromium
```
## 核心操作模式
### 1. 页面导航
```python
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# 基础导航
page.goto('https://example.com')
page.wait_for_load_state('networkidle')
# 带超时和重试
page.goto('https://example.com', timeout=30000)
# 等待特定元素
page.wait_for_selector('.content-loaded')
```
### 2. 元素交互
```python
# 点击
page.click('button#submit')
page.click('text=登录')
# 输入文本
page.fill('input[name="username"]', 'user@example.com')
page.fill('input[name="password"]', 'password123')
# 选择下拉框
page.select_option('select#city', value='beijing')
# 复选框
page.check('input[type="checkbox"]#agree')
# 文件上传
page.set_input_files('input[type="file"]', '/path/to/file.pdf')
# 键盘操作
page.keyboard.press('Enter')
page.keyboard.press('Control+A')
```
### 3. 数据提取
```python
# 单个元素文本
text = page.text_content('.title')
# 属性值
href = page.get_attribute('a.link', 'href')
# 多个元素
items = page.query_selector_all('.item')
data = []
for item in items:
data.append({
'title': item.text_content('.item-title'),
'price': item.text_content('.item-price'),
'link': item.get_attribute('a', 'href')
})
# 使用 evaluate 执行JS
result = page.evaluate('''() => {
return Array.from(document.querySelectorAll('.item')).map(el => ({
title: el.querySelector('.title')?.textContent,
price: el.querySelector('.price')?.textContent
}))
}''')
```
### 4. 截图
```python
# 全页面截图
page.screenshot(path='full-page.png', full_page=True)
# 元素截图
element = page.query_selector('.chart')
element.screenshot(path='chart.png')
# 指定区域
page.screenshot(path='clip.png', clip={'x': 0, 'y': 0, 'width': 800, 'height': 600})
```
### 5. 多标签/多页面
```python
# 新标签页
with page.context.expect_page() as new_page_info:
page.click('a[target="_blank"]')
new_page = new_page_info.value
new_page.wait_for_load_state()
# 多页面并行
context = browser.new_context()
pages = [context.new_page() for _ in range(5)]
```
### 6. 网络拦截
```python
# 拦截请求
page.route('**/*.{png,jpg,jpeg}', lambda route: route.abort()) # 屏蔽图片
# 修改请求头
page.set_extra_http_headers({'Accept-Language': 'zh-CN,zh;q=0.9'})
# 监听响应
responses = []
page.on('response', lambda r: responses.append(r))
```
### 7. 等待策略
```python
# 等待元素出现
page.wait_for_selector('.data-loaded', state='visible')
# 等待元素消失
page.wait_for_selector('.loading-spinner', state='hidden')
# 等待网络空闲
page.wait_for_load_state('networkidle')
# 自定义等待
page.wait_for_function('document.querySelectorAll(".item").length > 10')
```
## 反检测策略
```python
# stealth 配置
context = browser.new_context(
viewport={'width': 1920, 'height': 1080},
user_agent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) ...',
locale='zh-CN',
timezone_id='Asia/Shanghai'
)
# 模拟人类行为
import random, time
page.click('button', delay=random.randint(50, 200))
time.sleep(random.uniform(0.5, 1.5))
```
## 错误处理
```python
from playwright.sync_api import TimeoutError as PlaywrightTimeout
try:
page.wait_for_selector('.result', timeout=10000)
except PlaywrightTimeout:
# 超时处理:截图 + 重试
page.screenshot(path='timeout-debug.png')
page.reload()
page.wait_for_selector('.result', timeout=10000)
```
## 最佳实践
- 优先使用 `headless=True` 提升性能
- 使用 `wait_for_selector` 替代固定 `sleep`
- 大数据抓取使用请求拦截而非页面渲染
- 合理使用并发(控制在5个以内)
- 异常时自动截图便于调试
- 遵守 robots.txt 和网站使用条款支持平台:Qoder · QoderWork · Claude · Codex 等 AI 编程助手