在同一個版本的 selenium 升級 chrome 74 到 chrome 75 之後,遇到一個問題,還在想要不要去 google chromedriver 去開bug:
http://chromedriver.chromium.org/help
問題是,以前在存取 browser.url 時:
driver.current_url
如果遇到 UnexpectedAlertPresentException 只是會產生 exception 畫面會停在 alert / popup / confirm dialog 上,但v75之後,目前新的版本還會把 alert dismiss() 或 accept() 掉。
ChromeDriver 下載:
http://chromedriver.chromium.org/downloads
目前 ChromeDriver v75 有2個版本:
- ChromeDriver 75.0.3770.90 (2019-06-13)
- ChromeDriver 75.0.3770.8 (2019-04-29)
目前都有這一個問題。
workaround 解法,先花 0.1 秒去等待,看有沒有已經存在被彈出來的 alert:
What I do is to set a conditional delay with WebDriverWait just before the point I expect to see the alert, then switch to it, like this:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
browser = webdriver.Firefox()
browser.get("url")
browser.find_element_by_id("add_button").click()
try:
WebDriverWait(browser, 3).until(EC.alert_is_present(),
'Timed out waiting for PA creation ' +
'confirmation popup to appear.')
alert = browser.switch_to.alert
alert.accept()
print("alert accepted")
except TimeoutException:
print("no alert")
WebDriverWait(browser,
3)
will wait for at least 3 seconds for a supported alert to appear.