【问题标题】:How to accept alert that is triggered by 'get' in selenium (python, chromedriver)?如何接受由硒(python,chromedriver)中的“get”触发的警报?
【发布时间】:2016-10-26 10:21:23
【问题描述】:

我正在尝试使用 selenium 从某个页面导航到另一个页面:

driver = webdriver.Chrome()
driver.get("...some page...")
...  # the alert does not exist yet and thus cannot be accepted
driver.get("...some other page...") # the alert pops up here and blocks navigation to 'some other page'
# execution never reaches here
...

现在,离开“某个页面”会触发警报,要求确认用户是否真的想离开该页面。这会永远阻止执行。设置了隐式超时,但不会由此触发。我无法让 selenium 接受警报,因为只在调用 'get' 后出现。

有没有办法解决这个问题?

非常感谢!

【问题讨论】:

  • 为什么不能接受警报?显示代码你如何尝试接受它
  • 我无法接受警报,因为它只在调用get 后出现。然后执行被卡住。所以我在调用get之前既不能接受警报,因为它还不存在,也不能在之后接受,因为执行永远不会超过get
  • 但是,您可以接受此警报。那么你如何尝试接受它呢?向我们展示您使用的代码示例
  • 我会更改问题以使其更清楚
  • 我在问题的代码中添加了一些 cmets。现在清楚了吗?

标签: python selenium selenium-chromedriver


【解决方案1】:

尝试以下代码,如果它不起作用,请告诉我

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

driver = webdriver.Chrome()
driver.get("...some page...")
try:
    WebDriverWait(driver, 5).until(EC.alert_is_present())
    driver.switch_to_alert().accept()
except TimeoutException:
    print("Alert not found. Move on...)
driver.get("...some other page...")

【讨论】:

  • 感谢您的帮助!但这并不能解决它,因为直到driver.get("...some other page...") 才会弹出警报。
  • 所以不要在driver.get("...some page...")之后使用try/except块,而是在driver.get("...some other page...")之后使用
  • 这也不起作用,因为执行只在driver.get("...some other page") 处停止(它似乎被警报阻止了),因此不会到达try/except
  • 您尝试过还是只是您的建议?脚本执行不能被警报阻止!
  • 你是对的。事实证明问题出在其他地方,我匆忙下结论。很抱歉造成混乱,再次感谢您的帮助!最后它把我引向了问题的核心。
【解决方案2】:

试试overwritingjavascriptalert函数。

driver.get('https://stackoverflow.com/questions/40259660/how-to-accept-alert-that-is-triggered-by-get-in-selenium-python-chromedriver#40259660')
wmd_input = ref_settings.driver.find_element(By.ID, 'wmd-input')
wmd_input.click()
wmd_input.send_keys('That's a test for a model JS dialog')

#the following line overwrites the alert function
driver.execute_script("""window.alert = function() {};alert = function() {};""")
time.sleep(3)
ref_settings.driver.get('http://stackoverflow.com')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多