【web自動化測試】Playwright快速入門,5分鐘上手

我喜歡Playwright! 這是微軟開源的一款非常強大的自動化工具,再過幾年,他很有可能取代Selenium在瀏覽器自動化的通知地位。使用過一段時間,我沒有找到很好的中文資料可以參考,導致很多問題無法得到及時解決,因此我決定自己記錄一下使用的筆記,算是給社區回饋。

開始

這次我想整理一下如何快速搭建Playwright的執行環境,其中有一些坑,我也會記錄,以後重新搭環境的時候照着操作就可以了。
Playwright 目前支持的編程語言有 JavaScript、Python、Java、.NET,本教程使用 Python 語言演示。要在 Python 語言當中使用 Playwright,需要執行兩個步驟。第一步,安裝python的執行環境。第二步,安裝 Playwright。

安裝

安裝python只需要從官方網站下載安裝包,點擊安裝就可以完成。首先我們打開python的官方網站,然後點擊 download 下載安裝包。不同的操作系統會推薦不同的安裝包。下載完成後點擊安裝文件完成安裝。
image-20211016135042776
安裝 Playwright
Playwright 的 Python語言安裝包幾乎包含了所有需要用到的組件,安裝 playwright 工具唯一需要做的事情就是打開命令行工具,輸入安裝指令:

	  pip install playwright
	  playwright install

pip install playwright 安裝語言包工具,除此之外,playwright 需要依賴瀏覽器環境才能運行,playwright install 的意思是下載和安裝依賴的瀏覽器。瀏覽器不需要提前安裝,通過這行命令,程序會自動下載一個 chrioum 瀏覽器和一個 firefox 瀏覽器,之後的瀏覽器操作都會在這些瀏覽器上運行。耐心等待瀏覽器下載完成後,就完成了安裝,以後每次運行不會再重複下載。

如果覺得等待時間太長,也可以選擇單獨安裝 chromium 瀏覽器或者 firefox 瀏覽器,目前支持的瀏覽器有chromium, chrome, chrome-beta, msedge, msedge-beta, msedge-dev, firefox, webkit。

	  playwright install chromium
	  # or
	  playwright install firefox

所有關於 playwright 的命令行參數,你都可以通過 help 指令查看:

	  $ playwright --help
	  
	  Usage: npx playwright [options] [command]
	  
	  Options:
	  -V, --version                          output the version number
	  -h, --help                             display help for command
	  
	  Commands:
	  open [options] [url]                   open page in browser specified via -b, --browser
	  codegen [options] [url]                open page and generate code for user actions
	  install [options] [browser...]         ensure browsers necessary for this version of Playwright are installed
	  install-deps [browser...]              install dependencies necessary to run browsers (will ask for sudo permissions)
	  cr [options] [url]                     open page in Chromium
	  ff [options] [url]                     open page in Firefox
	  wk [options] [url]                     open page in WebKit
	  screenshot [options] <url> <filename>  capture a page screenshot
	  pdf [options] <url> <filename>         save page as pdf
	  show-trace [options] [trace]           Show trace viewer
	  help [command]                         display help for command

運行

當安裝好 Playwright 以及瀏覽器之後,我們可以通過下面的代碼來簡單運行。這個程序會打開一個瀏覽器,並且訪問一個網址,然後你就可以在瀏覽器上執行操作了。你做的每步操作,都會被 playwright 錄製下來,生成運行代碼,顯示在一個 Inspector 的界面中,這些代碼可以拷貝下來,保存到代碼庫當中。

	  playwright codegen http://www.baidu.com

image-20211015163629001

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章