LoginSignup
6
1

More than 3 years have passed since last update.

Selenium for Python Elementにフォーカスを当てる

Last updated at Posted at 2019-07-10

はじめに

Seleniumで要素をクリックするとフォーカスが移るものだと思っていました。
挙動を監視していると、どうもそうではないように思える事が多々あります。
そこで確実にフォーカスを移す方法を考えてみました。

実装

JavaScriptとPythonを使って実現します。

JavaScript

実際にファーカスを移す処理はJavaScriptで行います。
ここでは、以下のような記述にしてみました。

javascript
arguments[0].focus({"preventScroll": arguments[1]})

Python

上記のJavaScriptをSeleniumから呼び出します。

python
def focusToElement(driver, by, value, preventScroll):
  JavaScriptFocusToElement = "arguments[0].focus({'preventScroll': arguments[1]})"
  element = driver.find_element(by, value)
  driver.execute_script(JavaScriptFocusToElement, element, preventScroll)

実際に使う場合は、以下のようになります。

python
focusToElement(driver, By.XPATH, "//input[@name='cat']", True)

最後に

フォーカスを移す処理を入れてみたら既存のプログラムの安定性が上がりました。
また、スクロールの挙動がおかしかったのが治りました。
明示的にフォーカスを当てるのも考えて方が良いかもしれません。

6
1
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
6
1