Home > Back-end >  Selenium wait for presence of nested element query
Selenium wait for presence of nested element query

Time:01-29

In Selenium you can wait for a DOM element to load using WebDriverWait and EC.presence_of_element()

WebDriverWait(driver, 5).until(
    EC.presence_of_element_located((By.TAG_NAME, 'button')))

However, this queries the entire DOM. This does not suit scenarios where you have multiple button's on the the page and are querying for a specific one. The presence_of_element_located() will trigger on the first instance of a button

<body>
    <div >
        <button>Sign In!</button>
    </div>
    <div >
        <button>play!</button> <!-- The button we care about-->
    </div>
</body>

I want to perform a WebDriverWait for a the button inside of .controls specifically

Selenium allows you to perform nested queries by chaining .find_element()

control_button = driver.find_element(
    By.CLASS_NAME, 'controls').find_element(
        By.TAG_NAME, 'button')

is there a comparable technique for presence_of_element()?

CodePudding user response:

Solution 1

Using By.CSS_SELECTOR

WebDriverWait(driver, 5).until(
    EC.presence_of_element_located((
        By.CSS_SELECTOR, '.controls button')))

Solution 2

Passing the parent WebElement as the driver to the WebDriverWait()

controls = driver.find_element(By.CLASS_NAME, 'controls')

WebDriverWait(controls, 5).until(
    EC.presence_of_element_located((By.TAG_NAME, 'button')))

Related:

  • Related