Marios
Marios

Reputation: 27348

Selenium WebDriverWait with expected conditions returns only the first found element (Python)

I have the following html elements:

1)

<span class="input-group-btn">
        <button type="submit" class="btn btn-default" data-qa- 
id="main- 
go-button">Go</button>
      </span>

2)

<span class="input-group-btn" style="float: left;"><button type="button" 
wkda-autocomplete-update="update" class=" btn btn-default" data-qa- 
id="">Change</button></span>

3)

<span class="input-group-btn"><button type="button" wkda-autocomplete- 
update="update" class=" btn btn-default" data-qa-id="">Change</button></span>

The regular element finder:

browser.find_elements_by_class_name("input-group-btn")

returns a list of three items, since there are three html parts that contain the same structure:

[<selenium.webdriver.remote.webelement.WebElement 
(session="1fc51e63b34c7acfa37e3930c86fc46c", element="6bab5131-a508-41da- 
a7b7-1ccaae8dabda")>,
<selenium.webdriver.remote.webelement.WebElement 
(session="1fc51e63b34c7acfa37e3930c86fc46c", element="26dfeaa3-d54c-4652- 
a84e-aae47d0574ba")>,
<selenium.webdriver.remote.webelement.WebElement 
(session="1fc51e63b34c7acfa37e3930c86fc46c", element="7bb98d81-a576-41fd- 
be70-2aa2564f76b9")>]

I would like to select and click only the third element of this list, so I do:

browser.find_elements_by_class_name("input-group-btn")[2].text

and it works fine.

I would like though to find this element via the WebDriverWait. But when I run this:

WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.CLASS_NAME, "input-group-btn")))

it finds only the first element of the previous list, so it returns the first element found, but I would like to get the third one.

Do you know if there is any way to grab the third element instead of the first one found?

Upvotes: 2

Views: 119

Answers (2)

KunduK
KunduK

Reputation: 33384

To click on last change button.Induce WebdriverWait and following XPATH.

WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,"(//span[@class='input-group-btn']/button[text()='Change'])[last()]"))).click()

Upvotes: 1

CEH
CEH

Reputation: 5909

You will need a more specific selector to find your element. Since there are 3 elements found with browser.find_elements_by_class_name("input-group-btn"), you should write a more specific XPath selector. You don't need to wait for all 3 -- just for your specific button.

Based on the sample you provided, you could use the XPath //button[text()='Change']:

WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.XPath, "//button[text()='Change']")))
browser.find_element_by_xpath("//button[text()='Change']").text

Depending on what the HTML for 3rd button looks like, you can modify this XPath to suit your needs.

Upvotes: 1

Related Questions