OpenClaw 入门教程

openclaw openclaw解答 2

OpenClaw 是一个基于 Python 的轻量级自动化工具,主要用于 Web 抓取和自动化操作,以下是完整的入门指南:

OpenClaw 入门教程-第1张图片-官方openclaw下载|openclaw官网-国内ai小龙虾下载

安装 OpenClaw

方法 1:使用 pip 安装

pip install openclaw

方法 2:从源码安装

git clone https://github.com/openclaw/openclaw.git
cd openclaw
pip install -e .

基本概念

1 核心组件

  • Agent: 执行自动化任务的主体
  • Skill: 可重用的功能模块
  • Task: 具体的操作任务
  • Memory: 存储和记忆数据

快速开始示例

1 基础使用

from openclaw import OpenClaw
# 创建实例
claw = OpenClaw()
# 执行简单的浏览器自动化
claw.open("https://www.example.com")
claw.click('//button[@id="submit"]')
content = claw.extract('//div[@class="content"]')
print(content)

2 配置选项

from openclaw import OpenClaw
claw = OpenClaw(
    headless=False,          # 显示浏览器界面
    timeout=30,              # 超时时间
    user_agent="Mozilla/5.0", # 自定义User-Agent
    proxy="http://proxy:8080" # 使用代理
)

核心功能详解

1 页面操作

# 导航
claw.open("https://example.com")
claw.go_back()
claw.go_forward()
claw.refresh()
# 等待
claw.wait(5)  # 等待5秒
claw.wait_for_element('//div[@id="loading"]', timeout=10)

2 元素操作

# 查找元素
element = claw.find_element('//input[@name="username"]')
# 交互操作
claw.click('//button[@id="login"]')
claw.type('//input[@id="search"]', 'OpenClaw')
claw.select('//select[@id="country"]', 'CN')
claw.checkbox('//input[@type="checkbox"]', True)
# 获取信息
text = claw.get_text('//h1')
attr = claw.get_attribute('//img', 'src')
value = claw.get_value('//input')

3 数据提取

# 提取单个元素= claw.extract('//title/text()')
# 提取多个元素
items = claw.extract_all('//div[@class="item"]/text()')
# 提取结构化数据
data = claw.extract_dict({: '//h1/text()',
    'content': '//div[@class="content"]/text()',
    'links': ['//a/@href']
})
# 使用CSS选择器
claw.extract_css('div.post > h2')

4 文件操作

# 下载文件
claw.download('//a[@download]/@href', 'file.pdf')
# 上传文件
claw.upload('//input[@type="file"]', '/path/to/file.jpg')
# 截图
claw.screenshot('page.png')
claw.screenshot_element('//div[@id="widget"]', 'widget.png')

高级特性

1 任务链

from openclaw import TaskChain
tasks = TaskChain([
    {'action': 'open', 'url': 'https://example.com'},
    {'action': 'click', 'selector': '//a[@class="next"]'},
    {'action': 'extract', 'selector': '//div[@class="data"]'}
])
results = claw.execute_chain(tasks)

2 自定义技能

from openclaw.skills import Skill
class LoginSkill(Skill):
    def execute(self, username, password):
        self.claw.type('//input[@name="username"]', username)
        self.claw.type('//input[@name="password"]', password)
        self.claw.click('//button[@type="submit"]')
        return self.claw.check_exists('//div[@class="welcome"]')
# 注册和使用技能
claw.register_skill('login', LoginSkill)
success = claw.use_skill('login', username='user', password='pass')

3 反反爬虫策略

claw = OpenClaw(
    stealth=True,              # 启用隐身模式
    random_delay=True,         # 随机延迟
    human_like=True,           # 模拟人类行为
    rotate_user_agent=True     # 轮换User-Agent
)
# 使用代理池
claw.set_proxy_pool([
    'http://proxy1:8080',
    'http://proxy2:8080',
    'http://proxy3:8080'
])

完整示例

1 爬取电商网站

from openclaw import OpenClaw
import json
def scrape_products():
    claw = OpenClaw(headless=True)
    try:
        claw.open("https://example-shop.com/products")
        products = []
        page = 1
        while True:
            print(f"正在爬取第 {page} 页...")
            # 提取产品信息
            items = claw.extract_all('//div[@class="product-item"]')
            for item in items:
                product = {
                    'name': claw.extract('.//h3/text()', element=item),
                    'price': claw.extract('.//span[@class="price"]/text()', element=item),
                    'url': claw.extract('.//a/@href', element=item)
                }
                products.append(product)
            # 检查是否有下一页
            if not claw.check_exists('//a[@class="next-page"]'):
                break
            claw.click('//a[@class="next-page"]')
            claw.wait_for_element('//div[@class="product-item"]')
            page += 1
        # 保存数据
        with open('products.json', 'w', encoding='utf-8') as f:
            json.dump(products, f, ensure_ascii=False, indent=2)
        print(f"共爬取 {len(products)} 个产品")
    finally:
        claw.quit()
if __name__ == "__main__":
    scrape_products()

2 自动化测试

from openclaw import OpenClaw
def test_login():
    claw = OpenClaw(headless=False)
    try:
        claw.open("https://example.com/login")
        # 测试登录功能
        claw.type('//input[@name="email"]', 'test@example.com')
        claw.type('//input[@name="password"]', 'password123')
        claw.click('//button[@type="submit"]')
        # 验证登录成功
        claw.wait_for_element('//div[@class="dashboard"]', timeout=10)
        if claw.check_exists('//h1[contains(text(), "Welcome")]'):
            print("✓ 登录测试通过")
        else:
            print("✗ 登录测试失败")
    except Exception as e:
        print(f"测试出错: {e}")
        claw.screenshot('error.png')
    finally:
        claw.quit()
test_login()

最佳实践

1 错误处理

from openclaw.exceptions import TimeoutException, ElementNotFound
try:
    claw.click('//button[@id="submit"]')
except TimeoutException:
    print("操作超时")
except ElementNotFound:
    print("元素未找到")
except Exception as e:
    print(f"未知错误: {e}")

2 性能优化

# 批量操作
claw.batch_operations([
    ('click', '//button1'),
    ('type', '//input', 'text'),
    ('click', '//button2')
])
# 使用内存缓存
claw.enable_cache(ttl=3600)  # 缓存1小时
# 异步操作(如果支持)
async def async_scrape():
    async with AsyncOpenClaw() as claw:
        await claw.async_open("https://example.com")
        data = await claw.async_extract('//div')

3 日志记录

import logging
logging.basicConfig(level=logging.INFO)
claw = OpenClaw(
    log_level=logging.DEBUG,
    log_file='claw.log'
)

常见问题

Q1: 如何处理动态加载的内容?

# 方法1:等待JavaScript执行
claw.wait_for_ajax()  # 等待Ajax请求完成
claw.wait_for_dom_ready()  # 等待DOM加载完成
# 方法2:滚动加载
claw.scroll_to_bottom()
claw.wait(2)
# 方法3:触发事件
claw.trigger_event('//button[@id="load-more"]', 'click')

Q2: 如何处理验证码?

# 方法1:手动处理
claw.pause()  # 暂停,手动操作
input("请手动处理验证码后按回车继续...")
# 方法2:使用第三方服务(需要配置)
claw.solve_captcha('//img[@id="captcha"]', service='2captcha', api_key='your_key')

Q3: 如何保持会话?

# 保存和加载cookies
claw.save_cookies('cookies.json')
# 下次使用时
claw.load_cookies('cookies.json')

资源推荐

  1. 官方文档: https://openclaw.readthedocs.io
  2. GitHub仓库: https://github.com/openclaw/openclaw
  3. 示例项目: https://github.com/openclaw/examples
  4. 社区讨论: Discord 或 GitHub Discussions

注意事项

  1. 遵守网站的 robots.txt
  2. 控制请求频率,避免给服务器造成压力
  3. 尊重网站的使用条款
  4. 不要用于非法用途
  5. 考虑使用代理避免IP被封

这个教程涵盖了 OpenClaw 的主要功能和用法,建议从简单示例开始,逐步尝试更复杂的功能。

标签: OpenClaw 入门教程

抱歉,评论功能暂时关闭!