0
4

Selenium操作で完全Headlessを実現するためのいくつかのTips

Last updated at Posted at 2024-01-01

PythonでSeleniumを用いる際、必ずしもGUIが使用できる環境ばかりではありません。クラウド環境はもちろん、ローカル環境でもバックグラウンドで実行できたほうが何かと都合良いでしょう。そう考えると、何も考えずにPyaoutguiなどを用いていると思った通りの挙動となりません。今年一年、そういった作業を多くしてきたので、それで蓄積されたノウハウをまとめておきたいと思います。

1. Formへのデータ入力はまずsend_keys(→Enter)を試す

input_elem.send_keys(new_value)
input_elem.send_keys(Keys.ENTER) # send_keysだけでは入力確定にならない場合

2. send_keys.clear()が効かないときは全て選択してDelete

input_elem.send_keys(Keys.COMMAND, 'a')
input_elem.send_keys(Keys.DELETE)
input_elem.send_keys(new_price)

3. どうしてもマウス移動が必要ならActionChainsを試す

from selenium.webdriver import ActionChains

mouse_xpath = 'some_xpath' # hover状態にするためのpath
click_xpath = 'other_xpath' # hoverで出現した要素のpath

# マウスポインタを要素の位置に移動
element_to_move = driver.find_element(By.XPATH, mouse_xpath)
actions = ActionChains(driver)
actions.move_to_element(element_to_move).perform()

# 要素をクリック
element_to_click = driver.find_element(By.XPATH, click_xpath)
element_to_click.click()

4. WebDriverWait + EC で要素の出現と同時に取得

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

anchor_elem = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, some_anchor_xpath))
)
anchor_url = anchor_elem.get_attribute('href')

5. Window.Alertを操作する

some_button.click() # アラートのトリガーとなる動作
# アラートに対応するために待機
WebDriverWait(driver, 10).until(EC.alert_is_present())
time.sleep(3)

# アラートにスイッチし、'Enter'に相当する操作を実行
alert = driver.switch_to.alert
alert.accept()

6. スクロールしたいときはJSを使う

# スクロール対象の要素までスクロールするJavaScriptコード
scroll_script = "arguments[0].scrollIntoView();"
scroll_target = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, 'some_xpath')))
driver.execute_script(scroll_script, scroll_target)

7. elem.clickが効かないときもJSを使う

click_target_elem = WebDriverWait(driver, 10).until(EC.presence_of_element_located(
    (By.XPATH, 'some_xpath')))
driver.execute_script("arguments[0].click();", click_target_elem)
0
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
4