Playwright.devices()函数如何使用python代码示例
时间: 2024-06-10 15:05:35 浏览: 251
您好,使用Playwright.devices()函数获取设备信息的Python示例代码可以如下:
```
from playwright.sync_api import Playwright, sync_playwright
import random
# 随机获取一个设备信息
def random_device(playwright: Playwright) -> dict:
devices = playwright.devices
return devices[random.randint(0, len(devices)-1)]
with sync_playwright() as p:
# 初始化浏览器
browser = p.chromium.launch()
# 创建页面
page = browser.new_context(**random_device(p)).new_page()
# 在页面中执行操作
page.goto("https://www.baidu.com/")
page.fill("#kw", "playwright")
page.click("#su")
print(page.title())
# 关闭浏览器
browser.close()
```
以上代码示例演示了如何随机选择一个设备信息,并在页面中打开百度并搜索关键字“playwright”。请注意,此代码要求您已安装Playwright Python库,并已安装Playwright浏览器驱动程序。
阅读全文