目录
同步(Sync)模式
在同步模式下,代码按照传统的线性模式从上到下的顺序执行,每个操作都会阻塞直到完成后才去执行下面的代码。
同步时导入from playwright.sync_api import sync_playwright,使用with sync_playwright()创建上下文操作对象。
from playwright.sync_api import sync_playwright, Playwright, expect
def documentManage(playwright: Playwright, url):
browser = playwright.chromium.launch(headless=False)
context = browser.new_context(storage_state="cookies.json") # 传入storage_state参数,加载cookies
page = context.new_page()
page.goto(url, wait_until='commit', timeout=50000)
page.set_viewport_size({'width': 1920, 'height': 1080})
page.wait_for_timeout(3000)
context.close()
browser.close()
with sync_playwright() as p:
documentManage(p, 'http://172.168.52.27:18001/#/documentManage')
异步(Async)模式
异步模式是利用Python的asyncio库,允许非阻塞的并发操作。所以在等待某个耗时操作的同时,程序可以继续执行其他任务。需要使用await关键字来等待异步操作的结果。异步模式能显著提高脚本的执行效率,尤其是在大量网络请求或同时管理多个页面(浏览器实例)的场景下。异步执行可以更好地利用系统资源,减少运行时间。
异步需要导入from playwright.async_api import async_playwright,使用with async_playwright()创建上下文操作对象。
代码中需要使用异步编程库asyncio中的async进行异步函数的定义,每个要执行的语句需要使用await关键字等待异步执行的结果返回。为了测试下面代码中将每个调用方法的窗口大小和页面强制等待时长设为随机数,方便观察。
import random
import asyncio
from playwright.async_api import async_playwright, Playwright, expect
host = 'http://172.168.52.27:18001/#/'
apis = ['documentManage', 'home', 'incomingResult', 'materialFile', 'customerQualityComplain',
'abnormalBatchReturnList', 'customerLedger']
async def test(url):
print(f'开始{url}')
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False)
context = await browser.new_context(storage_state="cookies.json")
page = await context.new_page()
await page.set_viewport_size({'width': random.randint(500, 1920), 'height': random.randint(500, 1080)})
await page.goto(url)
await page.wait_for_timeout(random.randint(1, 10) * 1000)
await context.close()
await browser.close()
print(f'结束{url}')
async def main():
task1 = asyncio.create_task(test(f'{host}{apis[0]}'))
task2 = asyncio.create_task(test(f'{host}{apis[1]}'))
task3 = asyncio.create_task(test(f'{host}{apis[2]}'))
task4 = asyncio.create_task(test(f'{host}{apis[3]}'))
task5 = asyncio.create_task(test(f'{host}{apis[4]}'))
task6 = asyncio.create_task(test(f'{host}{apis[5]}'))
tasks = [task1, task2, task3, task4, task5, task6]
print('----------开始执行----------')
await asyncio.gather(*tasks)
print('----------结束运行----------')
asyncio.run(main())


2637

被折叠的 条评论
为什么被折叠?



