アクション
はじめに
Playwrightは、テキスト入力、チェックボックス、ラジオボタン、選択オプション、マウスのクリック、文字入力、キーとショートカット、ファイルのアップロード、要素へのフォーカスなど、HTML入力要素とインタラクトできます。
テキスト入力
locator.fill() を使用するのが、フォームフィールドに入力する最も簡単な方法です。これにより要素にフォーカスが当たり、入力されたテキストで input イベントがトリガーされます。これは <input>、<textarea>、および [contenteditable] 要素で機能します。
- 同期
- 非同期
# Text input
page.get_by_role("textbox").fill("Peter")
# Date input
page.get_by_label("Birth date").fill("2020-02-02")
# Time input
page.get_by_label("Appointment time").fill("13:15")
# Local datetime input
page.get_by_label("Local time").fill("2020-03-02T05:15")
# Text input
await page.get_by_role("textbox").fill("Peter")
# Date input
await page.get_by_label("Birth date").fill("2020-02-02")
# Time input
await page.get_by_label("Appointment time").fill("13:15")
# Local datetime input
await page.get_by_label("Local time").fill("2020-03-02T05:15")
チェックボックスとラジオボタン
locator.set_checked() を使用するのが、チェックボックスまたはラジオボタンをチェック/アンチェックする最も簡単な方法です。このメソッドは input[type=checkbox]、input[type=radio]、および [role=checkbox] 要素で使用できます。
- 同期
- 非同期
# Check the checkbox
page.get_by_label('I agree to the terms above').check()
# Assert the checked state
expect(page.get_by_label('Subscribe to newsletter')).to_be_checked()
# Select the radio button
page.get_by_label('XL').check()
# Check the checkbox
await page.get_by_label('I agree to the terms above').check()
# Assert the checked state
await expect(page.get_by_label('Subscribe to newsletter')).to_be_checked()
# Select the radio button
await page.get_by_label('XL').check()
選択オプション
locator.select_option() を使用して、<select> 要素で1つまたは複数のオプションを選択します。オプションの value または label を指定して選択できます。複数のオプションを選択できます。
- 同期
- 非同期
# Single selection matching the value or label
page.get_by_label('Choose a color').select_option('blue')
# Single selection matching the label
page.get_by_label('Choose a color').select_option(label='Blue')
# Multiple selected items
page.get_by_label('Choose multiple colors').select_option(['red', 'green', 'blue'])
# Single selection matching the value or label
await page.get_by_label('Choose a color').select_option('blue')
# Single selection matching the label
await page.get_by_label('Choose a color').select_option(label='Blue')
# Multiple selected items
await page.get_by_label('Choose multiple colors').select_option(['red', 'green', 'blue'])
マウスのクリック
単純な人間によるクリックを実行します。
- 同期
- 非同期
# Generic click
page.get_by_role("button").click()
# Double click
page.get_by_text("Item").dblclick()
# Right click
page.get_by_text("Item").click(button="right")
# Shift + click
page.get_by_text("Item").click(modifiers=["Shift"])
# Hover over element
page.get_by_text("Item").hover()
# Click the top left corner
page.get_by_text("Item").click(position={ "x": 0, "y": 0})
# Generic click
await page.get_by_role("button").click()
# Double click
await page.get_by_text("Item").dblclick()
# Right click
await page.get_by_text("Item").click(button="right")
# Shift + click
await page.get_by_text("Item").click(modifiers=["Shift"])
# Ctrl + click on Windows and Linux
# Meta + click on macOS
await page.get_by_text("Item").click(modifiers=["ControlOrMeta"])
# Hover over element
await page.get_by_text("Item").hover()
# Click the top left corner
await page.get_by_text("Item").click(position={ "x": 0, "y": 0})
内部的には、これおよび他のポインター関連のメソッドは、
- 指定されたセレクターを持つ要素がDOMに存在することを待つ
- 表示されるようになるのを待つ(つまり、空ではない、
display:noneではない、visibility:hiddenではない) - 移動が停止するのを待つ(たとえば、CSSトランジションが終了するまで)
- 要素をビューにスクロールする
- アクションポイントでポインターイベントを受信するのを待つ(たとえば、要素が他の要素によって隠されなくなるまで待つ)
- 上記のチェック中に要素がデタッチされた場合は再試行する
クリックを強制する
アプリによっては、要素にホバーすると、クリックをインターセプトする別の要素がオーバーレイされるという複雑なロジックを使用する場合があります。この動作は、要素がカバーされ、クリックが別の場所にディスパッチされるというバグと区別できません。この状況が発生していることを知っている場合は、アクション可能性チェックをバイパスして、クリックを強制することができます。
- 同期
- 非同期
page.get_by_role("button").click(force=True)
await page.get_by_role("button").click(force=True)
プログラムによるクリック
アプリを実際の条件下でテストすることに興味がなく、可能な限りあらゆる手段でクリックをシミュレートしたい場合は、locator.dispatch_event() を使用して要素にクリックイベントをディスパッチするだけで、HTMLElement.click() の動作をトリガーできます。
- 同期
- 非同期
page.get_by_role("button").dispatch_event('click')
await page.get_by_role("button").dispatch_event('click')
文字を入力する
ほとんどの場合、locator.fill() を使用してテキストを入力する必要があります。上記のテキスト入力セクションを参照してください。ページに特別なキーボード処理がある場合にのみ、文字を入力する必要があります。
locator.press_sequentially() を使用して、実際のキーボードを持つユーザーのように、フィールドに文字を1文字ずつ入力します。
- 同期
- 非同期
# Press keys one by one
page.locator('#area').press_sequentially('Hello World!')
# Press keys one by one
await page.locator('#area').press_sequentially('Hello World!')
このメソッドは、必要なすべてのキーボードイベント(keydown、keyup、keypressイベントを含む)を発行します。キー押下間のオプションのdelayを指定して、実際のユーザーの動作をシミュレートすることもできます。
キーとショートカット
- 同期
- 非同期
# Hit Enter
page.get_by_text("Submit").press("Enter")
# Dispatch Control+Right
page.get_by_role("textbox").press("Control+ArrowRight")
# Press $ sign on keyboard
page.get_by_role("textbox").press("$")
# Hit Enter
await page.get_by_text("Submit").press("Enter")
# Dispatch Control+Right
await page.get_by_role("textbox").press("Control+ArrowRight")
# Press $ sign on keyboard
await page.get_by_role("textbox").press("$")
locator.press() メソッドは、選択された要素にフォーカスし、単一のキーストロークを生成します。キーボードイベントの keyboardEvent.key プロパティで発行される論理キー名を受け入れます。
Backquote, Minus, Equal, Backslash, Backspace, Tab, Delete, Escape,
ArrowDown, End, Enter, Home, Insert, PageDown, PageUp, ArrowRight,
ArrowUp, F1 - F12, Digit0 - Digit9, KeyA - KeyZ, etc.
- あるいは、
"a"や"#"のような、生成したい単一の文字を指定することもできます。 - 以下の修飾ショートカットもサポートされています:
Shift、Control、Alt、Meta。
シンプルなバージョンは単一の文字を生成します。この文字は大文字と小文字を区別するため、"a"と"A"では異なる結果が生成されます。
- 同期
- 非同期
# <input id=name>
page.locator('#name').press('Shift+A')
# <input id=name>
page.locator('#name').press('Shift+ArrowLeft')
# <input id=name>
await page.locator('#name').press('Shift+A')
# <input id=name>
await page.locator('#name').press('Shift+ArrowLeft')
"Control+o"や"Control+Shift+T"のようなショートカットもサポートされています。修飾子とともに指定された場合、修飾子が押され、その後のキーが押されている間も保持されます。
大文字の文字を生成するには、Shift-Aで大文字のAを指定する必要があることに注意してください。Shift-aは、CapsLockがオンになっているかのように小文字の文字を生成します。
ファイルのアップロード
locator.set_input_files() メソッドを使用して、アップロードする入力ファイルを選択できます。最初の引数は、タイプ "file" の 入力要素を指すことを期待します。配列には複数のファイルを渡すことができます。ファイルパスの一部が相対パスの場合、それらは現在の作業ディレクトリを基準にして解決されます。空の配列は選択されたファイルをクリアします。
- 同期
- 非同期
# Select one file
page.get_by_label("Upload file").set_input_files('myfile.pdf')
# Select multiple files
page.get_by_label("Upload files").set_input_files(['file1.txt', 'file2.txt'])
# Select a directory
page.get_by_label("Upload directory").set_input_files('mydir')
# Remove all the selected files
page.get_by_label("Upload file").set_input_files([])
# Upload buffer from memory
page.get_by_label("Upload file").set_input_files(
files=[
{"name": "test.txt", "mimeType": "text/plain", "buffer": b"this is a test"}
],
)
# Select one file
await page.get_by_label("Upload file").set_input_files('myfile.pdf')
# Select multiple files
await page.get_by_label("Upload files").set_input_files(['file1.txt', 'file2.txt'])
# Select a directory
await page.get_by_label("Upload directory").set_input_files('mydir')
# Remove all the selected files
await page.get_by_label("Upload file").set_input_files([])
# Upload buffer from memory
await page.get_by_label("Upload file").set_input_files(
files=[
{"name": "test.txt", "mimeType": "text/plain", "buffer": b"this is a test"}
],
)
入力要素が手元にない場合(動的に作成される場合)、page.on("filechooser") イベントを処理するか、アクションに対応する待機メソッドを使用できます。
- 同期
- 非同期
with page.expect_file_chooser() as fc_info:
page.get_by_label("Upload file").click()
file_chooser = fc_info.value
file_chooser.set_files("myfile.pdf")
async with page.expect_file_chooser() as fc_info:
await page.get_by_label("Upload file").click()
file_chooser = await fc_info.value
await file_chooser.set_files("myfile.pdf")
要素にフォーカスを当てる
フォーカスイベントを処理する動的ページの場合、locator.focus() を使用して指定された要素にフォーカスを当てることができます。
- 同期
- 非同期
page.get_by_label('password').focus()
await page.get_by_label('password').focus()
ドラッグ&ドロップ
locator.drag_to() を使用してドラッグアンドドロップ操作を実行できます。このメソッドは
- ドラッグされる要素にホバーする。
- 左マウスボタンを押す。
- ドロップを受け取る要素にマウスを移動する。
- 左マウスボタンを離す。
- 同期
- 非同期
page.locator("#item-to-be-dragged").drag_to(page.locator("#item-to-drop-at"))
await page.locator("#item-to-be-dragged").drag_to(page.locator("#item-to-drop-at"))
手動でのドラッグ
ドラッグ操作を正確に制御したい場合は、locator.hover()、mouse.down()、mouse.move()、および mouse.up() などの低レベルメソッドを使用してください。
- 同期
- 非同期
page.locator("#item-to-be-dragged").hover()
page.mouse.down()
page.locator("#item-to-drop-at").hover()
page.mouse.up()
await page.locator("#item-to-be-dragged").hover()
await page.mouse.down()
await page.locator("#item-to-drop-at").hover()
await page.mouse.up()
ページが dragover イベントのディスパッチに依存している場合、すべてのブラウザでイベントをトリガーするには少なくとも2回のマウス移動が必要です。2回目のマウス移動を確実に発行するには、mouse.move() または locator.hover() を2回繰り返します。操作の順序は次のとおりです。ドラッグ要素にホバーし、マウスダウン、ドロップ要素にホバー、ドロップ要素に2回目ホバー、マウスアップ。
スクロール
ほとんどの場合、Playwrightはアクションを実行する前に自動的にスクロールを行います。したがって、明示的にスクロールする必要はありません。
- 同期
- 非同期
# Scrolls automatically so that button is visible
page.get_by_role("button").click()
# Scrolls automatically so that button is visible
await page.get_by_role("button").click()
しかし、まれに手動でスクロールする必要がある場合があります。例えば、「無限リスト」にさらに要素を読み込ませたい場合や、特定のスクリーンショットのためにページを配置したい場合などです。そのような場合、最も確実な方法は、下部に表示させたい要素を見つけて、それをビューにスクロールすることです。
- 同期
- 非同期
# Scroll the footer into view, forcing an "infinite list" to load more content
page.get_by_text("Footer text").scroll_into_view_if_needed()
# Scroll the footer into view, forcing an "infinite list" to load more content
await page.get_by_text("Footer text").scroll_into_view_if_needed()
スクロールをより正確に制御したい場合は、mouse.wheel() または locator.evaluate() を使用してください。
- 同期
- 非同期
# Position the mouse and scroll with the mouse wheel
page.get_by_test_id("scrolling-container").hover()
page.mouse.wheel(0, 10)
# Alternatively, programmatically scroll a specific element
page.get_by_test_id("scrolling-container").evaluate("e => e.scrollTop += 100")
# Position the mouse and scroll with the mouse wheel
await page.get_by_test_id("scrolling-container").hover()
await page.mouse.wheel(0, 10)
# Alternatively, programmatically scroll a specific element
await page.get_by_test_id("scrolling-container").evaluate("e => e.scrollTop += 100")