Home > OS >  How to to click button following xpath element? - python, selenium
How to to click button following xpath element? - python, selenium

Time:04-29

I'm trying to click the following button:

    <tr >
<td>
May 09 2022 09:00
</td>
<td>
Ecole 1337, Parc Tétouan Shore, commune de Martil, CP93150 – Tétouan
</td>
<td>
No spaces left
</td>
<td>
<a  id="js-piscine-17" href="/piscines/17/piscines_users">Add me to the waiting list</a>
</td>
</tr>

using the following code:

table = browser.find_element(By.CSS_SELECTOR, '#subs-content > table')
time.sleep(5)
plc = table.find_elements(By.XPATH, "//*[contains(text(),'Martil')]")[-1]
print(plc.text)
plc.click()

This piece of code does print the text but it does not click the desired button.
some people might ask: well, why don't you just use css selector or id of button?
but I'm expecting the website to be updated, and there would be more buttons which i would like my code to click, but i have no clue what their ids or css selectors would be. The only criteria is that it should have the word 'Martil' in it's "<tr>".

Edit: Thanks to @Dimitar, i was able to solve the problem using the following code:

table = browser.find_element(By.CSS_SELECTOR, '#subs-content > table')

for row in table.find_elements(By.TAG_NAME, 'tr')[::-1]:
    martil_row = row.find_element(By.XPATH, './/*[contains(text(), "Martil")]')
    if martil_row is not None:

        row.find_element(By.TAG_NAME, 'a').click()
        break

CodePudding user response:

The problem in your code is that you are finding "td" element which is not clickable. The clickable element is "a".

martil_rows = []
table = driver.find_element(By.CSS_SELECTOR, '#subs-content > table')
for row in table.find_elements(By.TAG_NAME, 'tr'):
    martil_row = row.find_element(By.XPATH, './/*[contains(text(), "Martil")]')
    if martil_row is not None:
        martil_rows.append(row.find_element(By.TAG_NAME, 'a'))

martil_rows[-1].click()
  • Related