Bootstrap

Playwright使用总结

Playwright使用总结

如何加载插件和用户数据

playwright加载插件

常用启动参数

with sync_playwright() as p:
    # 启动浏览器
    browser = p.chromium.launch(
        headless=headless,
        args=[
            # '--start-maximized',
            '--window-size=1920,1080'
            '--no-sandbox',
            '--disable-gpu'
        ]
    )

    # 打开页面
    context = browser.new_context(no_viewport=True)
    page = context.new_page()
	...
  • window-size,指定窗口大小。
  • no-sandbox,禁用沙箱。
  • disable-gpu,禁用GPU加速。在没有图形界面的服务器操作系统中,不添加这个选项可能无法启动浏览器。
  • start-maximized,最大化窗口运行,配合no_viewport=True一起使用才生效。

chromium其他常用参数
chromium所有配置参数

Page之间跳转

with context.expect_page() as new_page:
    # 点击按钮后打开新页面
    frame.locator('button[ecid="_Button@fyhj44@1_button@xq1ea3"]').click()
# page指向新页面
page = new_page.value

如何限制网速

在浏览器控制台中,可以配置网络速度。
在这里插入图片描述
在代码中使用cdp_session进行配置。

# 模拟网速
network_conditions = {
    'Offline': {
        'offline': True,
        'downloadThroughput': 0,
        'uploadThroughput': 0,
        'latency': 0,
        'connectionType': 'none'
    },
    "NoThrottle": {
        'offline': False,
        'downloadThroughput': -1,
        'uploadThroughput': -1,
        'latency': 0,
    },
    "Regular2G": {
        'offline': False,
        'downloadThroughput': (250 * 1024) / 8,
        'uploadThroughput': (50 * 1024) / 8,
        'latency': 300,
        'connectionType': 'cellular2g'
    },
    "Good2G": {
        'offline': False,
        'downloadThroughput': (450 * 1024) / 8,
        'uploadThroughput': (150 * 1024) / 8,
        'latency': 150,
        'connectionType': 'cellular2g'
    },
    "Regular3G": {
        'offline': False,
        'downloadThroughput': (750 * 1024) / 8,
        'uploadThroughput': (250 * 1024) / 8,
        'latency': 100,
        'connectionType': 'cellular3g'
    },
    "Good3G": {
        'offline': False,
        'downloadThroughput': (1.5 * 1024 * 1024) / 8,
        'uploadThroughput': (750 * 1024) / 8,
        'latency': 40,
        'connectionType': 'cellular3g'
    },
    "Regular4G": {
        'offline': False,
        'downloadThroughput': (4 * 1024 * 1024) / 8,
        'uploadThroughput': (3 * 1024 * 1024) / 8,
        'latency': 20,
        'connectionType': 'cellular4g'
    },
    "Wifi": {
        'offline': False,
        'downloadThroughput': (30 * 1024 * 1024) / 8,
        'uploadThroughput': (15 * 1024 * 1024) / 8,
        'latency': 2,
        'connectionType': 'wifi'
    },
}
# 设置网速
cdp_session = context.new_cdp_session(page)
cdp_session.send('Network.emulateNetworkConditions', network_conditions[network])
;