帮你快速理解、总结文档立即下载

手机操作

最近更新时间:2026-09-24 15:01:16
本文档已由 AI 辅助审校
我的收藏

前提条件

在执行下文所有代码前,请先按照 配置环境变量 部分完成环境变量设置。
使用手机沙箱实例前,您需要在 Agent 沙箱服务控制台 创建对应名称的手机沙箱工具,并将名称填入下列代码的 template 参数中。

手机操作

您可以通过 Appium 来连接并操作手机沙箱,通过 scrcpy_url 观察手机界面,实现自动化测试和操作。
下面的代码演示了如何通过 Appium 连接手机沙箱,并进行基本的操作(如打开手机中的浏览器、点击屏幕、截图等)。更多用法请参考 Appium 官方示例 和 Python Client SDK 文档。
Python

import os
import time
from pathlib import Path
from e2b import Sandbox
from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.webdriver.appium_connection import AppiumConnection

# 设置环境变量
os.environ["E2B_DOMAIN"] = "ap-shanghai.tencentags.com"
os.environ["E2B_API_KEY"] = "xxx"

# 创建一个手机沙箱,template 需要换为您在控制台创建的沙箱工具名称
sandbox = Sandbox.create(template="mobile-v1", timeout=600)
print(f"手机沙箱已创建: {sandbox.sandbox_id}")

# 获取 ws-scrcpy 屏幕流 URL
from urllib.parse import quote
scrcpy_host = sandbox.get_host(8000)
scrcpy_token = sandbox._envd_access_token
scrcpy_udid = "emulator-5554"
scrcpy_ws = f"wss://{scrcpy_host}/?action=proxy-adb&remote=tcp%3A8886&udid={scrcpy_udid}&access_token={scrcpy_token}"
scrcpy_url = f"https://{scrcpy_host}/?access_token={scrcpy_token}#!action=stream&udid={scrcpy_udid}&player=webcodecs&ws={quote(scrcpy_ws, safe='')}"
print(f"VNC 地址: {scrcpy_url}")


# 配置 Appium Driver
def AppiumDriver(sandbox, port: int = 4723, **options_kwargs):
options = UiAutomator2Options()
options.platform_name = options_kwargs.pop('platform_name', 'Android')
options.automation_name = options_kwargs.pop('automation_name', 'UiAutomator2')
options.new_command_timeout = 300

for key, value in options_kwargs.items():
setattr(options, key, value)

# 设置认证 header
AppiumConnection.extra_headers['X-Access-Token'] = sandbox._envd_access_token

return webdriver.Remote(
command_executor=f"https://{sandbox.get_host(port)}",
options=options
)

# 创建 Appium driver
driver = AppiumDriver(sandbox)
print(f"Appium 已连接,窗口大小: {driver.get_window_size()}")

# 1. 打开浏览器访问指定网页
url = "https://www.baidu.com/"
print(f"\\n打开浏览器访问: {url}")
driver.execute_script('mobile: shell', {
'command': 'am',
'args': ['start', '-a', 'android.intent.action.VIEW', '-d', url]
})
time.sleep(5) # 等待页面加载

# 2. 点击屏幕指定坐标
tap_x, tap_y = 360, 905
print(f"\\n点击屏幕坐标 ({tap_x}, {tap_y})...")
driver.execute_script('mobile: shell', {
'command': 'input',
'args': ['tap', str(tap_x), str(tap_y)]
})
time.sleep(300) # 等待操作完成

# 3. 截图保存
screenshot_dir = Path(__file__).parent / "screenshot"
screenshot_dir.mkdir(parents=True, exist_ok=True)
timestamp = time.strftime("%Y%m%d_%H%M%S")
screenshot_path = screenshot_dir / f"mobile_screenshot_{timestamp}.png"
driver.save_screenshot(str(screenshot_path))
print(f"\\n截图已保存: {screenshot_path}")

# 关闭
driver.quit()
sandbox.kill()