Search code examples
pythonselenium-webdriverxpath

Selenium XPATH doesn't press a clickable button


My problem is that the first on clicks while the second one doesn't and I don't understand why.

WebDriverWait(rootdiv, 10).until(EC.element_to_be_clickable((By.XPATH, "//li[@onclick[contains(.,JTC)]]")))

rootdiv.find_element_by_xpath("//li[@onclick[contains(.,'JTC')]]").click()

WebDriverWait(depdiv, 10).until(EC.element_to_be_clickable((By.XPATH, "//li[@onclick[contains(.,AJU)]]")))

depdiv.find_element_by_xpath("//li[@onclick[contains(.,'AJU')]]").click()

depdiv and rootdiv are children to find the certain li element in, because the root changes from the first to the second. I've checked that the div is visible and in the first one, it does click, but the second time it can't find the object and a time error is raised.

Here is the part of the code I'm trying to fed from:

<div class = "divCombo4">
   <ul><li>....</li><ul>
   <ul><li>...</li><ul>
</div>

My depdiv is rooting to find_element_by_id("divCombo4").

One of the ul li contains the following:

onclick="selecionou('AJU', this,'.txtBusca4', 'false', 'destino', 'Estouem2', 'AJU');"

Solution

  • First of all, you need a dot to make the expressions context-specific. Also, the wait.until() returns a WebElement instance and you can use it instead of issuing a "find element" command again:

    WebDriverWait(rootdiv, 10).until(EC.element_to_be_clickable((By.XPATH, ".//li[@onclick[contains(.,JTC)]]"))).click()
    
    WebDriverWait(depdiv, 10).until(EC.element_to_be_clickable((By.XPATH, ".//li[@onclick[contains(.,AJU)]]"))).click()