Skip to main content

Android

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();
})();

方法

¥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

要连接的浏览器 Websocket 端点。

¥A browser websocket endpoint to connect to.

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

¥Additional HTTP headers to be sent with web socket connect request. 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.

等待建立连接的最长时间(以毫秒为单位)。默认为 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


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


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

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

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

用于建立 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.

  • host string (optional) Added in: v1.45#

用于 Web 套接字的主机。它是可选的,如果省略它,服务器将在 IPv6 可用时接受未指定的 IPv6 地址 (::) 上的连接,否则接受未指定的 IPv4 地址 (0.0.0.0) 上的连接。考虑通过选择特定接口来强化它。

¥Host to use for the web socket. It is optional and if it is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise. Consider hardening it with picking a specific interface.

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

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

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

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

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

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

警告

任何了解 wsPath 的进程或网页(包括在 Playwright 中运行的进程或网页)都可以控制操作系统用户。因此,使用此选项时应使用不可猜测的令牌。:::

¥Any process or web page (including those running in Playwright) with knowledge of the wsPath can take control of the OS user. For this reason, you should use an unguessable token when using this option.

返回

¥Returns


setDefaultTimeout

Added in: v1.9 android.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