(已解决)python+selenium如何优雅地处理出现未知次数的弹框?

2019-10-21
问题有了变异,并最终确认是ChromeDriver版本不兼容的bug,我用的版本76.0.3809.25,同学的是2.43.600210(正确)。(chrome 77.0.3865.120)
详情见https://testerhome.com/topics/20940

2019-10-04
以下解法为ChromeDriver版本不兼容bug下的解法,非常不提倡。

<script>alert(1)</script>
<script>prompt(1)</script>
<script>confirm(1)</script>
<a href="https://www.baidu.com" target="_blank">baidu</a>

以上代码中的弹框出现未知次数(0-n),要求出现若干次弹框,最后均能正确返回driver.find_elements_by_xpath("//a")的结果

我的尝试:
driver.execute_script('window.alert=function(str){return;};'),这样重写不能实现目标。

from selenium import webdriver

chromeOptions = webdriver.ChromeOptions()
prefs={"profile.managed_default_content_settings.popups":0}
chromeOptions.add_experimental_option('prefs',prefs)
driver = webdriver.Chrome(chrome_options=chromeOptions)

domain = 'file:///C:/Users/admin/Desktop/popups.html'
driver.get(domain)

这样配置也不能实现目标。

我的处理代码已经跟我一样炸裂,就不发了。
我知道自定义chromium能实现禁止弹框,但还不想中途学习chromium源码编译。。。

并不优雅的解决方案:

clipboard.png

由于在有弹框的时候,在try下执行links = driver.find_elements_by_xpath("//a"),会报错

selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: 1

同时弹框自动消失,若此时执行driver.switch_to.alert.accept(),会触发不存在弹框的错误:

selenium.common.exceptions.NoAlertPresentException: Message: no such alert

所以我决定不对弹框进行操作,并不优雅的解决方案如下:

from selenium import webdriver

driver = webdriver.Chrome()
domain = 'file:///C:/Users/admin/Desktop/popups.html'
driver.get(domain)

for i in range(0,5):#允许弹框出现的次数,一直循环的直接放弃
    try:
        links = driver.find_elements_by_xpath("//a")
        break
    except Exception as e:
        if 'alert' in str(e):
            pass
        else:
            links = []
            break

print(links)

欢迎能用python解决的大佬继续解答。

阅读 4.6k
1 个回答

请参考代码片段

def find_by_xpath(driver, xpath):
    while True:
        try:
            return driver.find_elements_by_xpath(xpath)
        except UnexpectedAlertPresentException:
            try:
                driver.switchTo().alert().dismiss()
            except NoAlertPresentException:
                pass
            continue


links = find_by_xpath(driver, "//a")
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进