前提条件
手机操作
您可以通过 Appium 来连接并操作手机沙箱,通过
scrcpy_url观察手机界面,实现自动化测试和操作。下面的代码演示了如何通过 Appium 连接手机沙箱,并进行基本的操作(如打开手机中的浏览器、点击屏幕、截图等)。更多用法请参考 Appium 官方示例 和 Python Client SDK 文档。
import osimport timefrom pathlib import Pathfrom e2b import Sandboxfrom appium import webdriverfrom appium.options.android import UiAutomator2Optionsfrom 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 屏幕流 URLfrom urllib.parse import quotescrcpy_host = sandbox.get_host(8000)scrcpy_token = sandbox._envd_access_tokenscrcpy_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 Driverdef 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 = 300for key, value in options_kwargs.items():setattr(options, key, value)# 设置认证 headerAppiumConnection.extra_headers['X-Access-Token'] = sandbox._envd_access_tokenreturn webdriver.Remote(command_executor=f"https://{sandbox.get_host(port)}",options=options)# 创建 Appium driverdriver = AppiumDriver(sandbox)print(f"Appium 已连接,窗口大小: {driver.get_window_size()}")# 1. 打开浏览器访问指定网页url = "http://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, 905print(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()