python+playwright微軟自動(dòng)化工具的使用
它支持主流的瀏覽器,包含:Chrome、Firefox、Safari、Microsoft Edge 等,同時(shí)支持以無頭模式、有頭模式運(yùn)行
playwright-python 提供了同步、異步的 API,可以結(jié)合 Pytest 測(cè)試框架使用,并且支持瀏覽器端的自動(dòng)化腳本錄制
項(xiàng)目地址:https://github.com/microsoft/playwright-python
安裝playwright-python,執(zhí)行命令:pip install playwright
安裝成功之后,執(zhí)行命令:python -m playwright install,自動(dòng)下載 Chromeium、Firefox、Safari(WebKit)瀏覽器驅(qū)動(dòng)到本地
同步的關(guān)鍵字為:sync_playwright
比如,我們依次使用三個(gè)瀏覽器內(nèi)核打開瀏覽器,然后百度一下,接著對(duì)在搜索界面截圖,最后關(guān)閉瀏覽器
from time import sleep from playwright import sync_playwright # 注意:默認(rèn)是無頭模式 with sync_playwright() as p: # 分別對(duì)應(yīng)三個(gè)瀏覽器驅(qū)動(dòng) for browser_type in [p.chromium, p.firefox, p.webkit]: # 指定為有頭模式,方便查看browser = browser_type.launch(headless=False)page = browser.newPage()page.goto(’http://baidu.com’) # 執(zhí)行一次搜索操作page.fill('input[name='wd']', 'AirPython')with page.expect_navigation(): page.press('input[name='wd']', 'Enter') # 等待頁面加載完全page.waitForSelector('text=百度熱榜') # 截圖page.screenshot(path=f’example-{browser_type.name}.png’) # 休眠5ssleep(5) # 關(guān)閉瀏覽器browser.close()
需要指出的是,playwright-python 內(nèi)置的 API 基本上囊括常見的自動(dòng)化操作
異步異步步的關(guān)鍵字為:async_playwright
結(jié)合 asyncio,我們同時(shí)執(zhí)行上面的操作
import asyncio from playwright import async_playwright # 異步執(zhí)行async def main(): async with async_playwright() as p:for browser_type in [p.chromium, p.firefox, p.webkit]: # 指定為有頭模式,方便查看 browser = await browser_type.launch(headless=False) page = await browser.newPage() await page.goto(’http://baidu.com’) # 執(zhí)行一次搜索操作 await page.fill('input[name='wd']', 'AirPython') await page.press('input[name='wd']', 'Enter') # 等待頁面加載完全 await page.waitForSelector('text=百度熱榜') # 截圖 await page.screenshot(path=f’example-{browser_type.name}.png’) await browser.close() asyncio.get_event_loop().run_until_complete(main())
事實(shí)上,Playwright 是一個(gè)跨語言的自動(dòng)化框架,支持 Python、Java、JS 等
Playwright 相比傳統(tǒng)的自動(dòng)化框架 Selenium 來說,在 Context 上下文及 API 使用上,顯得更簡(jiǎn)潔且強(qiáng)大
到此這篇關(guān)于python+playwright微軟自動(dòng)化工具的使用的文章就介紹到這了,更多相關(guān)python playwright微軟自動(dòng)化工具內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
