3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Seleniumでクリック前に要素にスクロールさせる

Last updated at Posted at 2021-05-16

Selenium(Python)で要素をクリックする直前に、毎回要素までスクロールさせる処理を行うためのコードです。
このGoogle検索でスクロール処理させる必要は本来ないはずですが、例として書いています。

test.py
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener

#要素をクリックする直前の処理を定義
class CustomListener(AbstractEventListener):
    def before_click(self, element, driver):
        # 要素までスクロールさせる
        driver.execute_script('arguments[0].scrollIntoView({behavior: "smooth", block: "center"});', element)

# Webdriver ManagerでChromeDriverを取得
base_driver = webdriver.Chrome(ChromeDriverManager().install())
driver = EventFiringWebDriver(base_driver, CustomListener())

# Google検索で「Selenium」の検索結果を1〜10ページ目まで表示
driver.get('https://www.google.com/search?q=selenium')
for i in range(2, 11):
    driver.find_element_by_xpath("//a[@aria-label='Page " + str(i) +"']").click()

driver.close()
driver.quit()

参考

3
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?