简体   繁体   English

如何点击 xpath 元素后面的按钮? - python, selenium

[英]How to to click button following xpath element? - python, selenium

I'm trying to click the following button:我正在尝试单击以下按钮:

    <tr class="">
<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 class="btn btn-primary" 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?有些人可能会问:那你为什么不直接使用 css 选择器或按钮的 id?
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.但我希望网站得到更新,并且会有更多按钮,我希望我的代码可以单击这些按钮,但我不知道它们的 ID 或 css 选择器是什么。 The only criteria is that it should have the word 'Martil' in it's "<tr>".唯一的标准是它的“<tr>”中应该有“Martil”这个词。

Edit: Thanks to @Dimitar, i was able to solve the problem using the following code:编辑:感谢@Dimitar,我能够使用以下代码解决问题:

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

The problem in your code is that you are finding "td" element which is not clickable.您的代码中的问题是您找到了不可点击的“td”元素。 The clickable element is "a".可点击元素是“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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM