python palywright庫基本使用
開源方:微軟
安裝:pip install playwright;python -m playwright install
特點:自動化腳本錄制;有同步、異步api
生成代碼指令:python -m playwright codegen
其他:需要Python 3.7及以上;官方api為node版本,python版本待補充
同步:關鍵字為:sync_playwright
from time import sleep from playwright import sync_playwright with sync_playwright() as p: for browser_type in [p.chromium, p.firefox, p.webkit]: browser = browser_type.launch(headless=False) # 默認無頭,這樣為有頭模式 page = browser.newPage() page.goto('http://baidu.com') 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') sleep(5) browser.close()
異步:關鍵字為:async_playwright
import asyncio from playwright import async_playwright 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') 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())
集成 pytest 測試
@pytest.fixture(scope="session") def test_playwright_is_visible_on_google(page): page.goto("https://www.google.com") page.type("input[name=q]", "Playwright GitHub") page.click("input[type=submit]") page.waitForSelector("text=microsoft/Playwright")
執行 JS 代碼
from playwright import sync_playwright with sync_playwright() as p: browser = p.firefox.launch() page = browser.newPage() page.goto('https://www.example.com/') dimensions = page.evaluate('''() => { return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight, deviceScaleFactor: window.devicePixelRatio } }''') print(dimensions) browser.close()
中斷網絡請求
from playwright import sync_playwright with sync_playwright() as p: browser = p.chromium.launch() page = browser.newPage() def log_and_continue_request(route, request): print(request.url) route.continue_()
記錄並繼續所有網絡請求
page.route('**', lambda route, request: log_and_continue_request(route, request)) page.goto('http://todomvc.com') browser.close()
以上就是python palywright庫基本使用的詳細內容,更多關於python palywright庫的資料請關註WalkonNet其它相關文章!
推薦閱讀:
- python+playwright微軟自動化工具的使用
- Playwright快速上手指南(入門教程)
- 微軟開源最強Python自動化神器Playwright(不用寫一行代碼)
- 詳解Python初學者神器Playwright如何使用
- 一款強大的端到端測試工具Playwright介紹