前言
当我们打开有的网站,网站会请求权限,比如某些网站要进进行声音采集或者开启摄像头时,都会弹出一个权限请求框,如下图:
这种权限请求与alert弹框不同,并不是在页面上,所以selenium无法处理这种弹框,但是playwright却可以实现对这些权限请求弹框的处理。本文就给大家介绍一下playwright对这些权限弹框的处理。
grant_permissions()
playwright的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".
"""
使用示例
我们以使用计算机的麦克风和摄像头功能为例,代码如下:
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')
运行脚本,我们即可实现为网站添加摄像头以及麦克风的权限。
总结
本文主要介绍了playwright对于需要添加权限的网站的处理,这是playwright相比于selenium的一大优势,因为selenium无法处理页面外的内容,所以无法处理权限的请求,但是playwright却可以实现该操作。