首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于alert_is_present()和switch_to_alert()的函数

用于alert_is_present()和switch_to_alert()的函数
EN

Stack Overflow用户
提问于 2020-02-05 20:47:19
回答 2查看 1.9K关注 0票数 0

我有代码(python / selenium):

代码语言:javascript
复制
    # Alert start
    WebDriverWait(self.driver, 5).until(EC.alert_is_present())
    self.driver.switch_to_alert().dismiss()
    # Alert end

第一行在浏览器中等待警报,第二行按下“取消”按钮关闭此窗口。它工作得很好。我决定创建两个函数。

代码语言:javascript
复制
    def alertIsPresent(self, timeout=10):
        WebDriverWait(self.driver, timeout).until(EC.alert_is_present())

    def alertDismiss(self):
        alert = self.driver.switch_to_alert()
        alert.dismiss()

我把这个函数叫做:

代码语言:javascript
复制
    PageObject.alertIsPresent()
    PageObject.alertDismiss()

最后一个")“加了下划线,因为”参数自填“...我是python的新手,你能给我一些建议吗?

pageObjectClass:

代码语言:javascript
复制
class PageObject:

def __init__(self, driver, xpathLocator):
    self.driver = driver
    self.locator = xpathLocator
    self.wait = WebDriverWait(self.driver, 100)

def waitElementToBePresent(self, timeout=10):
    WebDriverWait(self.driver, timeout).until(
        EC.visibility_of_element_located((By.XPATH, self.locator)))

def elementIsPresent(self):
    return EC.visibility_of_element_located((By.XPATH, self.locator))

def alertIsPresent(self, timeout=10):
    WebDriverWait(self.driver, timeout).until(EC.alert_is_present())

def alertDismiss(self):
    alert = self.driver.switch_to_alert()
    alert.dismiss()
EN

回答 2

Stack Overflow用户

发布于 2020-02-05 21:48:58

您还没有提到Seleniumpython客户端的版本信息。

但是,根据当前的实现和documentation

代码语言:javascript
复制
switch_to

SwitchTo: an object containing all options to switch focus into

Usage: driver.switch_to.alert

因此,您需要有效地替换以下代码行:

代码语言:javascript
复制
alert = self.driver.switch_to_alert()

通过以下方式:

代码语言:javascript
复制
alert = self.driver.switch_to.alert
票数 1
EN

Stack Overflow用户

发布于 2020-02-05 22:10:33

不需要使用两个函数,EC.alert_is_present()将返回警报

代码语言:javascript
复制
def alertIsPresent(self, timeout=10):
    return WebDriverWait(self.driver, timeout).until(EC.alert_is_present())

您还需要从类实例调用它,而不是从类型

代码语言:javascript
复制
PageObject(driver).alertIsPresent().dismiss()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60076192

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档