Skip to main content

安卓

Playwright 对 Android 自动化提供实验性支持。这包括 Android 版 Chrome 和 Android WebView。

Playwright has experimental support for Android automation. This includes Chrome for Android and Android WebView.

要求

Requirements

  • Android 设备或 AVD 模拟器。

    Android device or AVD Emulator.

  • ADB 守护进程 正在运行并通过你的设备进行身份验证。通常,你只需运行 adb devices 即可。

    ADB daemon running and authenticated with your device. Typically running adb devices is all you need to do.

  • 设备上安装了 Chrome 87 或更高版本

    Chrome 87 or newer installed on the device

  • "在非 root 设备上启用命令行" 在 chrome://flags 中启用。

    "Enable command line on non-rooted devices" enabled in chrome://flags.

已知的限制

Known limitations

  • 尚不支持原始 USB 操作,因此你需要 ADB。

    Raw USB operation is not yet supported, so you need ADB.

  • 设备需要处于唤醒状态才能生成屏幕截图。启用 "保持清醒" 开发者模式会有帮助。

    Device needs to be awake to produce screenshots. Enabling "Stay awake" developer mode will help.

  • 我们没有针对该设备运行所有测试,因此并非一切正常。

    We didn't run all the tests against the device, so not everything works.

如何运行

How to run

Android 自动化脚本的示例如下:

An example of the Android automation script would be:

const { _android: android } = require('playwright');

(async () => {
// Connect to the device.
const [device] = await android.devices();
console.log(`Model: ${device.model()}`);
console.log(`Serial: ${device.serial()}`);
// Take screenshot of the whole device.
await device.screenshot({ path: 'device.png' });

{
// --------------------- WebView -----------------------

// Launch an application with WebView.
await device.shell('am force-stop org.chromium.webview_shell');
await device.shell('am start org.chromium.webview_shell/.WebViewBrowserActivity');
// Get the WebView.
const webview = await device.webView({ pkg: 'org.chromium.webview_shell' });

// Fill the input box.
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');

// Work with WebView's page as usual.
const page = await webview.page();
await page.waitForNavigation({ url: /.*microsoft\/playwright.*/ });
console.log(await page.title());
}

{
// --------------------- Browser -----------------------

// Launch Chrome browser.
await device.shell('am force-stop com.android.chrome');
const context = await device.launchBrowser();

// Use BrowserContext as usual.
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();
}

// Close the device.
await device.close();
})();

请注意,由于测试 Android 时不需要 Playwright 安装网页浏览器,因此你可以在安装 Playwright 时通过设置以下环境变量来省略浏览器下载:

Note that since you don't need Playwright to install web browsers when testing Android, you can omit browser download via setting the following environment variable when installing Playwright:

PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 npm i -D playwright

方法

Methods

connect

Added in: v1.28 android.connect

此方法将 Playwright 连接到现有的 Android 设备。使用 android.launchServer() 启动新的 Android 服务器实例。

This methods attaches Playwright to an existing Android device. Use android.launchServer() to launch a new Android server instance.

用法

Usage

await android.connect(wsEndpoint);
await android.connect(wsEndpoint, options);

参数

Arguments

  • wsEndpoint [string]#

要连接的浏览器 Websocket 端点。

A browser websocket endpoint to connect to.

  • options [Object] (optional)

    • headers [Object]<[string], [string]> (optional)#

与 Web 套接字连接请求一起发送的附加 HTTP 标头。可选的。

Additional HTTP headers to be sent with web socket connect request. Optional.

  • slowMo [number] (optional)#

将 Playwright 操作减慢指定的毫秒数。很有用,这样你就可以看到发生了什么。默认为 0

Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. Defaults to 0.

  • timeout [number] (optional)#

等待建立连接的最长时间(以毫秒为单位)。默认为 30000(30 秒)。通过 0 禁用超时。

Maximum time in milliseconds to wait for the connection to be established. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.

返回

Returns

  • [Promise]<[AndroidDevice]>#

devices

Added in: v1.9 android.devices

返回检测到的 Android 设备的列表。

Returns the list of detected Android devices.

用法

Usage

await android.devices();
await android.devices(options);

参数

Arguments

  • options [Object] (optional)

    • host [string] (optional) Added in: v1.22#

可选主机建立 ADB 服务器连接。默认为 127.0.0.1

Optional host to establish ADB server connection. Default to 127.0.0.1.

  • omitDriverInstall [boolean] (optional) Added in: v1.21#

防止在附加时自动安装 Playwright 驱动程序。假设驱动程序已安装。

Prevents automatic playwright driver installation on attach. Assumes that the drivers have been installed already.

  • port [number] (optional) Added in: v1.20#

用于建立 ADB 服务器连接的可选端口。默认为 5037

Optional port to establish ADB server connection. Default to 5037.

返回

Returns

  • [Promise]<[Array]<[AndroidDevice]>>#

launchServer

Added in: v1.28 android.launchServer

启动客户端可以连接的 Playwright Android 服务器。请参见以下示例:

Launches Playwright Android server that clients can connect to. See the following example:

用法

Usage

服务器端:

Server Side:

const { _android } = require('playwright');

(async () => {
const browserServer = await _android.launchServer({
// If you have multiple devices connected and want to use a specific one.
// deviceSerialNumber: '<deviceSerialNumber>',
});
const wsEndpoint = browserServer.wsEndpoint();
console.log(wsEndpoint);
})();

客户端:

Client Side:

const { _android } = require('playwright');

(async () => {
const device = await _android.connect('<wsEndpoint>');

console.log(device.model());
console.log(device.serial());
await device.shell('am force-stop com.android.chrome');
const context = await device.launchBrowser();

const page = await context.newPage();
await page.goto('https://webkit.org/');
console.log(await page.evaluate(() => window.location.href));
await page.screenshot({ path: 'page-chrome-1.png' });

await context.close();
})();

参数

Arguments

  • options [Object] (optional)

    • adbHost [string] (optional)#

可选主机建立 ADB 服务器连接。默认为 127.0.0.1

Optional host to establish ADB server connection. Default to 127.0.0.1.

  • adbPort [number] (optional)#

用于建立 ADB 服务器连接的可选端口。默认为 5037

Optional port to establish ADB server connection. Default to 5037.

  • deviceSerialNumber [string] (optional)#

用于启动浏览器的可选设备序列号。如果不指定,连接多个设备时会抛出异常。

Optional device serial number to launch the browser on. If not specified, it will throw if multiple devices are connected.

  • omitDriverInstall [boolean] (optional)#

防止在附加时自动安装 Playwright 驱动程序。假设驱动程序已安装。

Prevents automatic playwright driver installation on attach. Assumes that the drivers have been installed already.

  • port [number] (optional)#

用于网络套接字的端口。默认为 0,选择任何可用端口。

Port to use for the web socket. Defaults to 0 that picks any available port.

  • wsPath [string] (optional)#

为 Android 服务器提供服务的路径。为了安全起见,这默认为不可猜测的字符串。

Path at which to serve the Android Server. For security, this defaults to an unguessable string.

warning

wsPath can take control of the OS user. For this reason, you should use an unguessable token when using this option. :::任何了解以下内容的进程或网页(包括在 Playwright 中运行的进程或网页)

返回

Returns


setDefaultTimeout

Added in: v1.9android.setDefaultTimeout

此设置将更改所有接受 timeout 选项的方法的默认最大时间。

This setting will change the default maximum time for all the methods accepting timeout option.

用法

Usage

android.setDefaultTimeout(timeout);

参数

Arguments

最长时间(以毫秒为单位)

Maximum time in milliseconds