0

I have code (python / selenium):

    # Alert start
    WebDriverWait(self.driver, 5).until(EC.alert_is_present())
    self.driver.switch_to_alert().dismiss()
    # Alert end

The first row wait for alert in the browser and second row press "Cancel" button to dismiss this window. It works fine. I decided to create 2 functions.

    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()

And I call this functions:

    PageObject.alertIsPresent()
    PageObject.alertDismiss()

The last ")" is underlined because "parameter self unfilled"... I'm newest in python, can you give me suggestion?

pageObjectClass:

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()
JeffC
  • 22,180
  • 5
  • 32
  • 55
Igor-Potapov
  • 43
  • 2
  • 9

2 Answers2

2

No need to use two functions, EC.alert_is_present() will return the alert

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

You also need to call it from class instance, not type

PageObject(driver).alertIsPresent().dismiss()
Guy
  • 46,488
  • 10
  • 44
  • 88
1

You havn't mentioned the version information of the Selenium's client.

However, as per the the current implementation and documentation:

switch_to

SwitchTo: an object containing all options to switch focus into

Usage: driver.switch_to.alert

So, effectively, you need to replace the line:

alert = self.driver.switch_to_alert()

With:

alert = self.driver.switch_to.alert
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352