Android
Playwright 对 Android 自动化 提供 实验性 支持,包括 Android 上的 Chrome 浏览器和 Android WebView。
要求
- Android 设备或 AVD 模拟器。
- 已运行并通过身份验证的 ADB daemon(通常执行
adb devices即可)。 - 设备上已安装
Chrome 87或更高版本。 - 在
chrome://flags中启用了 "Enable command line on non-rooted devices"。
已知限制
- 目前不支持原始 USB 操作,需要使用 ADB。
- 设备需保持唤醒状态以生成截图,开启开发者选项中的 "Stay awake" 有帮助。
- 并非所有功能在真实设备上都已完全测试,可能存在不兼容情况。
使用方法
下面是一个 Android 自动化脚本示例:
const { _android: android } = require('playwright');
(async () => {
// 连接设备。
const [device] = await android.devices();
console.log(`Model: ${device.model()}`);
console.log(`Serial: ${device.serial()}`);
// 截取整机截图。
await device.screenshot({ path: 'device.png' });
{
// --------------------- WebView -----------------------
// 启动带有 WebView 的应用。
await device.shell('am force-stop org.chromium.webview_shell');
await device.shell('am start org.chromium.webview_shell/.WebViewBrowserActivity');
// 获取 WebView 实例。
const webview = await device.webView({ pkg: 'org.chromium.webview_shell' });
// 填写输入框。
await device.fill({ res: 'org.chromium.webview_shell:id/url_field' }, 'github.com/microsoft/playwright');
await device.press({ res: 'org.chromium.webview_shell:id/url_field' }, 'Enter');
// 像普通页面一样操作 WebView。
const page = await webview.page();
await page.waitForNavigation({ url: /.*microsoft\\/playwright.*/ });
console.log(await page.title());
}
{
// --------------------- Browser -----------------------
// 启动 Chrome 浏览器。
await device.shell('am force-stop com.android.chrome');
const context = await device.launchBrowser();
// 正常使用 BrowserContext。
const page = await context.newPage();
await page.goto('https://webkit.org/');
console.log(await page.evaluate(() => window.location.href));
await page.screenshot({ path: 'page.png' });
await context.close();
}
// 关闭设备连接。
await device.close();
})();
如果在安装 Playwright 时不希望下载桌面浏览器,可通过以下环境变量跳过浏览器下载:
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm i -D playwright
android.devices([options])
Added in: v1.9options?<Object>- returns: <Promise<Array<AndroidDevice>>>#
返回检测到的 Android 设备列表。
android.setDefaultTimeout(timeout)
Added in: v1.9此设置会影响所有接受 timeout 选项的方法的默认最大时间。