pythonseleniumexpected-condition

Selenium Combining multiple Expected conditions in Python


wait = (driver, 10)
wait.until(EC.presence_of_element_located((By.XPATH, '//td[@class="blah blah blah"]')))
wait.until(EC.visibility_of_element_located((By.XPATH, '//h1[text() = "yo yo"]')))

Is there a way to combine these two conditions into one line or any way that says if both of these conditions are true then only click() in Selenium, Python.


Solution

  • Here's an example of making a function for Selenium's WebDriverWait:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    
    # Open the website
    driver.get('https://ocrdata.ed.gov/flex/Reports.aspx?type=school')
    
    ... more code ...
    
    # Custom function for Explicit Wait
    # The Export button is available before it is "clickable", need to wait
    def find(driver):
        export_button = driver.find_element_by_name('ctl00$div$ucReportViewer$btnExport')
        if export_button:
            try: 
                export_button.click()
                return True
            except:
                return False
        else:
            return False
    
    secs = 120
    export_button = WebDriverWait(driver, secs).until(find)
    

    I would suggest recording the presence and visibility of both elements as separate variables and creating an if statement in the function like so:

    # Custom function for Explicit Wait
    # The Export button is available before it is "clickable", need to wait
    def find(driver):
        presence = EC.presence_of_element_located((By.XPATH, '//td[@class="blah blah blah"]'))
        visibility = EC.visibility_of_element_located((By.XPATH, '//h1[text() = "yo yo"]'))
        if presence and visibility:
            try: 
                # action
                return True
            except:
                return False
        else:
            return False
    
    secs = 120
    export_button = WebDriverWait(driver, secs).until(find)