前言
有些场景在使用的时候,会弹出一些权限框,比如麦克风和摄像头等,通过监听alert 是没法捕获的。
正确做法是给浏览器设置默认允许麦克风和摄像头等权限,不让弹窗出来。使用context 的 grant_permissions 方法加权限。
权限框
弹窗示例
这种弹窗是权限窗,不是alert
解决办法
context 有个 grant_permissions 方法可以加权限,常见的权限如下
def grant_permissions(
self, permissions: typing.List[str], *, origin: typing.Optional[str] = None
) -> None:
"""BrowserContext.grant_permissions
Grants specified permissions to the browser context. Only grants corresponding permissions to the given origin if
specified.
Parameters
----------
permissions : List[str]
A permission or an array of permissions to grant. Permissions can be one of the following values:
- `'geolocation'`
- `'midi'`
- `'midi-sysex'` (system-exclusive midi)
- `'notifications'`
- `'camera'`
- `'microphone'`
- `'background-sync'`
- `'ambient-light-sensor'`
- `'accelerometer'`
- `'gyroscope'`
- `'magnetometer'`
- `'accessibility-events'`
- `'clipboard-read'`
- `'clipboard-write'`
- `'payment-handler'`
origin : Union[str, None]
The [origin] to grant permissions to, e.g. "https://example.com".
"""
添加'camera', 'microphone' 权限示例
from playwright.sync_api import sync_playwright
with sync_playwright() as playwright:
browser = playwright.chromium.launch(headless=False)
context = browser.new_context()
# 设置允许 'camera', 'microphone' 权限
context.grant_permissions(['camera', 'microphone'])
page = context.new_page()
page.goto('https://www.demo.com/demo.html')
2023最新《Playwright+Python自动化测试》点我 ->立即参与
联系微信:283340479