28
27

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 5 years have passed since last update.

Selenium で別ウィンドウが開くまで待つ

Posted at

問題

Selenium で Web ページを操作しています。あるリンクをクリックすると別ウィンドウが開き、そのウィンドウに制御を移したいです。

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('http://www.tagindex.com/html_tag/link/a_target.html')
driver.find_element_by_css_selector('[href="target_example.html"]').click()

driver.switch_to.window(driver.window_handles[1])

ただしこのコードでは driver.window_handles[1] が存在せずに IndexError で失敗することがあります :sob:

解決策

WebDriverWait.until() を使うことで、別ウィンドウが開くまで待機することができます。

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Chrome()
driver.get('http://www.tagindex.com/html_tag/link/a_target.html')
driver.find_element_by_css_selector('[href="target_example.html"]').click()

WebDriverWait(driver, 3).until(lambda d: len(d.window_handles) > 1)
driver.switch_to.window(driver.window_handles[1])

これにより確実に別ウィンドウに制御を移すことができます :blush:

28
27
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
28
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?