【Python3】Seleniumでキーボード操作を行う方法

おはこんばんにちは、せなです。

今回は、Seleniumでキーボード操作を行う方法を紹介します。

キーボード操作を行う方法

キーボード操作を行うには、ActionChainsを使用することで実現できます。
以下はgoogle.comを開いて検索ボックスに「selenium」と入力し、ENTERキーを送信するプログラムです。

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys

# Chromeを起動する
driver = webdriver.Chrome(ChromeDriverManager().install())

# google.comを開く
driver.get("https://google.com")

# ActionChainsをインスタンス化
action = webdriver.ActionChains(driver)

# 検索ボックスに入力を行う
action.send_keys("selenium").perform()

# 検索ボックスにEnterキーを送信する
action.send_keys(Keys.ENTER).perform()

# 検索できたことを確認するために5秒待つ
driver.implicitly_wait(5)

# ブラウザを閉じる
driver.quit()

キーボード操作の一覧

Seleniumではキーボードを操作するキーが用意されています。
以下はそのキーの一覧です。

キー説明
Keys.BACK_SPACEBackSpace
Keys.TABTab
Keys.ENTEREnter
Keys.SHIFTShift
Keys.CONTROLControl
Keys.ALTAlt
Keys.ESCAPEEscape
Keys.SPACESpace
Keys.PAGE_UPPageUp
Keys.PAGE_DOWNPageDown
Keys.ENDEnd
Keys.HOMEHome
Keys.LEFTLeft
Keys.RIGHTRight
Keys.UPUp
Keys.DOWNDown
Keys.INSERTInsert
Keys.DELETEDelete

最後に

Seleniumでキーボード操作を行う方法を説明して見ました。

ActionChainsを使用すると簡単に検索ボックスへの入力からエンターキーの実行までできるので便利ですね!

ではでは〜

Selenium,Python

Posted by sena