Seleniumで要素にキーコンビネーションを入力する
send_keys(Keys.修飾キー + 'キー')
#または
send_keys(Keys.修飾キー, 'キー')
のようにするとSeleniumでキーコンビネーション入力のシミュレートができる。
例:Google検索フォームに直前のクリップボードの内容をペーストして送信する。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
d = webdriver.Chrome()
d.get('https://www.google.com/')
element = d.find_element_by_name('q')
element.send_keys(Keys.CONTROL + 'v')
element.submit()
またはActionChainsクラスを使って
from selenium.webdriver.common.action_chains import ActionChains
element = d.find_element_by_name('q')
action = ActionChains(d)
action.key_down(Keys.CONTROL)
action.send_keys_to_element(element, 'v')
action.key_up(Keys.CONTROL)
action.send_keys_to_element(element, Keys.ENTER)
action.perform()
のように書くこともできる。
環境
- Selenium 3.141.0
- ChromeDriver 89.0.4389.23
- Google Chrome 89.0.4389.82
- Windows 10