OpenClaw 是一个功能强大的开源网络爬虫框架,专为数据采集和分析设计,以下是详细的使用教程:

安装与配置
安装
# 使用 pip 安装 pip install openclaw # 或者从源码安装 git clone https://github.com/openclaw/openclaw.git cd openclaw pip install -r requirements.txt python setup.py install
基本配置
import openclaw
# 初始化配置
config = {
'user_agent': 'Mozilla/5.0 (兼容爬虫)',
'request_timeout': 30,
'retry_times': 3,
'concurrent_requests': 5,
'proxy': None, # 可选代理设置
}
claw = openclaw.Claw(config)
基本使用
简单网页抓取
# 单页面抓取
url = "https://example.com"
response = claw.fetch(url)
print(f"状态码: {response.status_code}")
print(f"网页内容长度: {len(response.text)}")
print(f"内容预览: {response.text[:500]}")
# 解析 HTML
soup = claw.parse_html(response.text)= soup.find('title').text
数据提取
# 使用 CSS 选择器
data = claw.extract(response.text, {: 'h1.title',
'articles': [
{
'title': 'div.article h2',
'content': 'div.article p',
'date': 'span.date'
}
]
})
# 使用 XPath
data_xpath = claw.extract_with_xpath(response.text, {: '//h1[@class="title"]/text()',
'links': '//a/@href'
})
高级功能
批量爬取
# 定义爬虫任务
task = {
'start_urls': [
'https://example.com/page1',
'https://example.com/page2'
],
'callback': 'parse_page',
'next_page': '//a[@class="next"]/@href' # 自动翻页
}
def parse_page(response, data):
# 自定义解析逻辑
soup = claw.parse_html(response.text)
items = soup.select('div.item')
for item in items:
yield {
'title': item.select_one('h2').text,
'url': item.select_one('a')['href']
}
# 执行爬虫
results = claw.run_task(task, parse_page)
for result in results:
print(result)
动态页面处理
# 启用 JavaScript 渲染
claw.enable_js_rendering(
headless=True, # 无头模式
wait_time=3 # 等待页面加载时间
)
# 抓取动态内容
dynamic_content = claw.fetch_js(
url="https://spa.example.com",
wait_for="div.content-loaded" # 等待元素出现
)
数据存储
# 保存到 JSON claw.save_to_json(data, 'output.json') # 保存到 CSV claw.save_to_csv(data, 'output.csv') # 保存到数据库 import sqlite3 claw.save_to_database(data, 'sqlite:///data.db', table_name='articles')
配置进阶
请求设置
advanced_config = {
'headers': {
'Accept': 'text/html,application/xhtml+xml',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Referer': 'https://google.com'
},
'cookies': {
'session_id': 'your_session_id'
},
'delay': 1.5, # 请求间隔
'robots_txt': True, # 遵守 robots.txt
'max_depth': 3, # 爬取深度限制
}
代理设置
# 单代理
claw.set_proxy('http://user:pass@proxy.example.com:8080')
# 代理池
proxy_pool = [
'http://proxy1.example.com:8080',
'http://proxy2.example.com:8080',
'http://proxy3.example.com:8080'
]
claw.set_proxy_pool(proxy_pool, strategy='random') # 轮询策略
完整示例
import openclaw
import json
from datetime import datetime
class NewsSpider:
def __init__(self):
config = {
'user_agent': 'Mozilla/5.0 OpenClaw Bot/1.0',
'concurrent_requests': 3,
'delay': 2,
'timeout': 30
}
self.claw = openclaw.Claw(config)
def crawl_news(self, start_url):
"""爬取新闻网站"""
results = []
def parse_news(response):
soup = self.claw.parse_html(response.text)
# 提取新闻列表
news_items = soup.select('div.news-item')
for item in news_items:
news_data = {
'title': item.select_one('h2').text.strip(),
'url': item.select_one('a')['href'],
'summary': item.select_one('p.summary').text.strip()[:200],
'source': 'Example News',
'crawl_time': datetime.now().isoformat()
}
results.append(news_data)
yield news_data
# 查找下一页
next_page = soup.select_one('a.next-page')
if next_page:
next_url = next_page['href']
yield from self.claw.fetch_and_parse(next_url, parse_news)
# 开始爬取
for data in self.claw.fetch_and_parse(start_url, parse_news):
print(f"获取到新闻: {data['title']}")
# 保存结果
self.claw.save_to_json(results, 'news.json')
print(f"爬取完成,共获取 {len(results)} 条新闻")
return results
# 使用示例
if __name__ == '__main__':
spider = NewsSpider()
news = spider.crawl_news('https://news.example.com/latest')
最佳实践
遵守爬虫礼仪
- 设置合理的请求间隔
- 遵守网站的 robots.txt
- 识别并处理反爬机制
- 限制并发请求数量
错误处理
try:
response = claw.fetch(url)
if response.status_code == 200:
# 处理成功响应
data = claw.extract(response.text, selectors)
elif response.status_code == 403:
print("访问被拒绝,可能需要代理或验证")
elif response.status_code == 404:
print("页面不存在")
except Exception as e:
print(f"请求失败: {e}")
# 重试逻辑
性能优化
- 使用连接池
- 启用缓存
- 异步请求处理
- 分布式爬取
注意事项
- 法律合规:确保你的爬虫行为符合目标网站的服务条款和法律法规
- 资源消耗:合理控制爬取频率,避免对目标服务器造成过大压力
- 数据存储:注意用户隐私和数据安全
- 更新维护:网站结构变化时需要及时更新爬虫解析规则
故障排除
常见问题及解决方法:
- 请求被拒绝:检查 User-Agent、添加请求头、使用代理解析失败**:检查网页结构变化、更新选择器
- 内存占用过高:减少并发数、及时清理缓存
- 速度过慢:优化网络请求、使用异步处理
这个教程涵盖了 OpenClaw 的基本和进阶使用方法,实际使用时,建议参考官方文档获取最新功能和详细 API 说明。
版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。