Python?Playwright庫(kù)從入門到實(shí)戰(zhàn)教程
一、項(xiàng)目簡(jiǎn)介
Playwright是由微軟開發(fā)的現(xiàn)代化瀏覽器自動(dòng)化庫(kù),支持通過(guò)統(tǒng)一API控制Chromium、Firefox、WebKit三大瀏覽器引擎。其核心特性包括:
- 跨瀏覽器兼容性:一套代碼適配所有主流瀏覽器
- 自動(dòng)等待機(jī)制:智能等待元素就緒,告別隨機(jī)失敗
- 強(qiáng)大網(wǎng)絡(luò)控制:支持請(qǐng)求攔截、模擬和修改
- 移動(dòng)設(shè)備模擬:內(nèi)置50+種設(shè)備參數(shù),輕松適配移動(dòng)端
- 同步/異步雙模式:兼顧易用性與執(zhí)行效率
二、安裝部署
2.1 環(huán)境要求
- Python 3.7+
- Windows/MacOS/Linux系統(tǒng)
- 推薦使用Pytest作為測(cè)試框架
2.2 快速安裝
# 安裝核心庫(kù) pip install playwright # 下載瀏覽器二進(jìn)制文件(自動(dòng)識(shí)別系統(tǒng)環(huán)境) python -m playwright install # 安裝Pytest插件(可選) pip install pytest-playwright
2.3 驗(yàn)證安裝
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("https://playwright.dev")
print(page.title()) # 應(yīng)輸出 "Playwright"
browser.close()
三、核心功能詳解
3.1 基礎(chǔ)操作流程
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
# 啟動(dòng)瀏覽器(有頭模式便于調(diào)試)
browser = p.chromium.launch(headless=False)
# 創(chuàng)建新上下文(隔離環(huán)境)
context = browser.new_context()
# 打開頁(yè)面
page = context.new_page()
# 基礎(chǔ)操作示例
page.goto("https://baidu.com")
page.fill("input[name=wd]", "Playwright教程")
page.click("text=百度一下")
# 截圖保存
page.screenshot(path="search_result.png")
# 關(guān)閉資源
context.close()
browser.close()
3.2 元素定位策略
# 文本選擇器(推薦)
page.click("text=立即購(gòu)買")
# CSS選擇器
page.fill(".search-box", "關(guān)鍵詞")
# XPath選擇器
page.click('//button[@id="submit"]')
# 響應(yīng)式選擇器(自動(dòng)適配移動(dòng)端)
page.locator("button:visible").click()
3.3 高級(jí)功能實(shí)現(xiàn)
3.3.1 網(wǎng)絡(luò)請(qǐng)求攔截
def test_api_mock():
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
# 啟用請(qǐng)求攔截
page.route("**/api/data", lambda route: route.fulfill(
status=200,
json={"message": "Custom Response"}
))
page.goto("https://example.com")
assert page.locator(".data-display").text_content() == "Custom Response"
browser.close()
3.3.2 移動(dòng)設(shè)備模擬
def test_mobile_view():
with sync_playwright() as p:
iphone = p.devices['iPhone 12']
browser = p.chromium.launch()
# 創(chuàng)建移動(dòng)設(shè)備上下文
context = browser.new_context(
**iphone,
locale='zh-CN',
timezone_id='Asia/Shanghai'
)
page = context.new_page()
page.goto("https://m.taobao.com")
page.screenshot(path="mobile_view.png")
context.close()
browser.close()
3.3.3 異步執(zhí)行模式
import asyncio
from playwright.async_api import async_playwright
async def main():
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.goto("https://example.com")
await browser.close()
asyncio.run(main())
四、最佳實(shí)踐
4.1 測(cè)試組織策略
# pytest_playwright示例
import pytest
@pytest.fixture(scope="function")
def browser():
pw = sync_playwright().start()
browser = pw.chromium.launch()
yield browser
browser.close()
def test_search(browser):
page = browser.new_page()
page.goto("https://bing.com")
page.fill("input[name=q]", "Playwright最佳實(shí)踐")
page.click("text=搜索")
assert "Playwright最佳實(shí)踐" in page.content()
4.2 調(diào)試技巧
# 日志記錄配置
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
# 截圖輔助調(diào)試
try:
page.click("#submit")
except Exception as e:
page.screenshot(path="error_debug.png")
raise e
4.3 性能優(yōu)化
# 并行執(zhí)行配置(pytest.ini)
[pytest]
addopts = -n auto
# 資源復(fù)用
def test_parallel():
with sync_playwright() as p:
contexts = []
for _ in range(10):
contexts.append(p.chromium.launch().new_context())
# 并行執(zhí)行測(cè)試...
五、常見問(wèn)題解決
Q1: 安裝時(shí)提示"Permission denied"
A: 使用以下命令修復(fù)權(quán)限:
sudo chown -R $USER ~/.cache/playwright
Q2: 元素定位失敗
A: 嘗試以下方法:
# 增加等待時(shí)間
page.wait_for_selector(".target-element")
# 使用更魯棒的選擇器
page.locator("text=立即購(gòu)買 >> nth=0").click()
Q3: 如何處理登錄認(rèn)證
A: 使用存儲(chǔ)狀態(tài)功能:
context = browser.new_context(
storage_state="auth_state.json"
)
# 或手動(dòng)輸入憑證
page.fill("#username", "admin")
page.fill("#password", "123456")
page.click("#login")
六、總結(jié)
Playwright通過(guò)其現(xiàn)代化的設(shè)計(jì)和豐富的功能集,已成為Web自動(dòng)化領(lǐng)域的首選工具。其核心優(yōu)勢(shì)體現(xiàn)在:
- 跨瀏覽器一致性:統(tǒng)一API適配所有主流瀏覽器
- 開發(fā)效率:自動(dòng)等待和智能定位減少80%的調(diào)試時(shí)間
- 測(cè)試可靠性:內(nèi)置網(wǎng)絡(luò)模擬和移動(dòng)適配能力
- 生態(tài)完善:與Pytest等框架無(wú)縫集成
建議開發(fā)者從基礎(chǔ)操作入手,逐步掌握網(wǎng)絡(luò)攔截、設(shè)備模擬等高級(jí)功能,結(jié)合項(xiàng)目需求構(gòu)建完整的自動(dòng)化測(cè)試體系。
七、附錄
- 官方文檔:https://playwright.dev/python
- 設(shè)備參數(shù)表:https://playwright.dev/python/api/class-devices
- GitHub倉(cāng)庫(kù):https://github.com/microsoft/playwright-python
- 交流社區(qū):https://gitter.im/microsoft/playwright
到此這篇關(guān)于Python Playwright庫(kù)從入門到實(shí)戰(zhàn)的文章就介紹到這了,更多相關(guān)Python Playwright庫(kù)詳解內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python開源自動(dòng)化工具Playwright安裝及介紹使用
- Python中Playwright的常用操作方法分享
- Python?Playwright的使用詳解
- Python自動(dòng)化神器Playwright的用法詳解
- Python寫UI自動(dòng)化之playwright(點(diǎn)擊操作)詳解
- Python Playwright安裝和基本使用問(wèn)題記錄
- python+playwright微軟自動(dòng)化工具的使用
- Python?Playwright進(jìn)行常見的頁(yè)面交互操作
- Python中Playwright模塊進(jìn)行自動(dòng)化測(cè)試的實(shí)現(xiàn)
相關(guān)文章
Python隨手筆記之標(biāo)準(zhǔn)類型內(nèi)建函數(shù)
Python提供了一些內(nèi)建函數(shù)用于基本對(duì)象類型:cmp(),repr(),str(),type()和等同于repr()的(' ')操作符,本文給大家分享Python隨手筆記之標(biāo)準(zhǔn)類型內(nèi)建函數(shù),對(duì)python內(nèi)建函數(shù)相關(guān)知識(shí)感興趣的朋友一起學(xué)習(xí)吧2015-12-12
Queue隊(duì)列中join()與task_done()的關(guān)系及說(shuō)明
這篇文章主要介紹了Queue隊(duì)列中join()與task_done()的關(guān)系及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
基于python實(shí)現(xiàn)數(shù)組格式參數(shù)加密計(jì)算
這篇文章主要介紹了基于python實(shí)現(xiàn)數(shù)組格式參數(shù)加密計(jì)算,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
python configparser中默認(rèn)值的設(shè)定方式
這篇文章主要介紹了python configparser中默認(rèn)值的設(shè)定方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
Python為何不能用可變對(duì)象作為默認(rèn)參數(shù)的值
這篇文章主要介紹了Python為何不能用可變對(duì)象作為默認(rèn)參數(shù)的值,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07

