2024年1月29日 星期一

WebDriver 使用筆記

紀錄一下自己在使用瀏覽器 Web Driver 的筆記。

Web Driver 上網查的話,基本上都會告訴你這東西就是模擬瀏覽器,你可以在那進行各種操作。

但,網路上的範例都是 python code,對於厭惡 python 的人,例如我,就非常不友好。

Gecko driver

我自己基本上都是使用 geckodriver 的。

所以筆記也是以 Gecko driver為主。

Session

在 Web Driver,一個 Session 相當於「一個獨立的瀏覽器設定」。

說的更通俗點,當我新建一個 Web Driver Session ,相當於瀏覽器新增一個臨時的設定檔,然後以該設定檔來進行操作。

所以要使用 Web Driver ,第一步就是建立 Session。

新建 Session

首先先執行 Web Driver:

C:\> geckodriver.exe
1706514153464   geckodriver     INFO    Listening on 127.0.0.1:4444

出現下面那段文字,表示 geckodriver 正常啟動,接下來使用 127.0.0.1:4444 進行各種操作。

想換成別的 port,就用 --port參數:

C:\> geckodriver --port 6060
1706515137092   geckodriver     INFO    Listening on 127.0.0.1:6060

接著,送出以下的 Request :

網址 127.0.0.1:4444/session
Header Content-Type: application/json
Method POST
Request Body
{
	"capabilities": {
		"alwaysMatch": {
			"moz:firefoxOptions": {
				"binary": "C:/Program Files/Mozilla Firefox/firefox.exe"
			}
		}
	}
}

如果執行成功,就會出現以下的 Response Body:

{
	"value": {
		"sessionId": "6c806459-2ed9-45df-9dc7-c89bf2e69497",
		"capabilities": {
			/* 中略 */
		}
	}
}
關閉 Session

如果要關閉 Session,參閱W3C的說明,執行以下 Request 即可

網址 http://127.0.0.1:4444/session/{session id}
因為剛才的 ID 是 6c806459-2ed9-45df-9dc7-c89bf2e69497,所以這邊的 URL 就是
http://127.0.0.1:4444/session/6c806459-2ed9-45df-9dc7-c89bf2e69497
Method DELETE

關閉成功的話,geckodriver 會輸出以下 Response

{"value": null}
Headless

剛才寫的新增 Session 的 Request,會開啟一個 firefox 視窗。如果想以無頭模式處理,Request Body 改成如下

{
	"capabilities": {
		"alwaysMatch": {
			"moz:firefoxOptions": {
				"binary": "C:/Program Files/Mozilla Firefox/firefox.exe",
				"args": ["-headless"] // 加上這一行
			}
		}
	}
}

只要 FireFox 能使用的參數,例如 user-agent 等等的,應該也能依此類推。

Microsoft Edge WebDriver

下載點:Microsoft Edge WebDriver

Edge WebDriver 使用上和 Gecko Driver 差不多,比較不同的是建立 Session 時,他的 Request body 只要求要有 capabilities,但 capabilities 可以是空物件。即:

網址 127.0.0.1:9515/session

(Edge WebDriver 的默認 IP PORT 是 9515)
Header Content-Type: application/json
Method POST
Request Body
{
	"capabilities": {}
}
Headless

如果要建一個 Headless Session ,則 request body 如下:

{
	"capabilities": {
		"alwaysMatch": {
			"ms:edgeOptions": {
				"args": [
					"headless"
				]
			}
		}
	}
}

關於 ms:edgeOptions ,請參閱 learn / Microsoft Edge / Capabilities and EdgeOptions

參考資料

Simon , S., & David , B. (Eds.). (2024, January 23). WebDriver. W3C®. https://w3c.github.io/webdriver/
Christian , B. (2023, October 21). Capabilities. WebdriverIO Documentation. https://webdriver.io/docs/capabilities/
Geckodriver: Usage. (n.d.). Firefox Source Docs. https://firefox-source-docs.mozilla.org/testing/geckodriver/Usage.html#Running-Firefox-in-an-container-based-package
Msedgeteam, Mikehoffms, Yanlingwang23, Captainbrosset, Zoherghadyali, Vchapel, Bwalderman, & jm-trd-ms. (2023, May 13). Capabilities and EdgeOptions. Microsoft Learn. https://learn.microsoft.com/en-us/microsoft-edge/webdriver-chromium/capabilities-edge-options

沒有留言:

張貼留言