Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

Playwright

由微軟扶持,Selenium的勁敵。

Playwright 常用指令

  • 等待元素可見
1
page.wait_for_selector('input[type="file"]', state='visible')
  • 等頁面加載
1
page.wait_for_load_state(state='networkidle')
  • 斷言
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 檢查元素是否可見
assert page.is_visible('selector')
# 驗證文本內容
assert page.text_content('h1') == '預期標題'

# 定位文件輸入元素
file_input = page.locator('[id=""]')
# 設置要上傳的文件
file_input.set_input_files(r'PATH')
time.sleep(3)
try:
assert file_input.count() > 0
print("文件上傳成功")
except:
print("文件上傳失敗")
  • 模擬網路請求
1
page.route('**/*', lambda route: route.fulfill(status=200, body='mocked data'))
  • 腳本錄製
1
playwright codegen --target python -o script.py -b chromium https://example.com
  • 模擬手動延遲
1
nput_locator.type("testInput", delay=100) 
  • 上傳檔案
1
2
3
4
5
6
# 定位文件輸入元素
file_input = page.locator('input[type="file"]')
# 設置要上傳的文件
file_input.set_input_files('/path/to/file.txt')
# 設置多個文件上傳
file_input.set_input_files(['/path/to/file1.txt', '/path/to/file2.txt'])

Playwright捕捉Growl

Primefaces的Growl就像Android的Toast,只出現一陣子就消失,為了捕捉到他,必須用點技巧

概念

  1. 提示訊息很快消失,DOM中程式也是如此,可以開著F12並錄影回放捕捉Class name
  2. 用wait_for(state=’attached’…等訊息跳出來

實作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 回放中顯示Growl的class name是ui-growl-item,捕捉並擷取訊息
error_message_locator = page.locator("div.ui-growl-item").filter(has_text="訊息")

# 使用 locator.wait_for 等待提示信息被附加到 DOM 中(最大等待時間為5秒)
error_message_locator.wait_for(state='attached', timeout=5000)

try:
# 斷言提示信息是否附加到了 DOM 中且可見
expect(error_message_locator).to_be_visible()
print("斷言成功")
except:
print("斷言失敗")

# 停在當前頁面
page.pause()

XPath

畫面中元素的地址,可以依以下步驟取得

  1. 開發者工具
  2. 面板左上選元素
  3. 複製完整地址

Python 程式碼入口比較

1
2
3
4
5
* if __name__ == "__main__"
* 通用,用於一般的Python程式入口設置,能夠幫助程式碼模組化,使之更容易測試和重用。

* with sync_playwright() as playwright
* 特定於 Playwright 庫,用於瀏覽器自動化腳本的資源管理和壽命週期控制。

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels