Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Selenium: Click on button based on text inside span tag

I want to click on this button when <Span text is "OK":

<button type="button" class="ant-btn ant-btn-primary" style="float: right;"><span>OK</span></button>

The soluton would be something like that (this code don´t work because it´s not clickable):

driver.find_element_by_xpath('//span[text()="OK"]').click()

I found a way that works, but I can´t garantee the text inside Span is "OK":

button =  driver.find_element_by_css_selector('#root > section > section > div.ant-row > div:nth-child(2) > div.ant-spin-nested-loading > div > div > div > div > div.ant-collapse-content.ant-collapse-content-active > div > div > div > div:nth-child(17) > button.ant-btn.ant-btn-primary')
button.click()

How can I click on buttons based on Span tag?

Edit: Button code line

like image 803
JohnB Avatar asked Jul 21 '26 10:07

JohnB


1 Answers

So, based on your button HTML

<button type="button" class="ant-btn ant-btn-primary" style="float: right;"><span>OK</span></button>

I think that the following xapth would help you.

//button[contains(@class, 'ant-btn-primary')]//*[contains(., 'OK')]/..

The /.. helps you traverse back 1 level; sending you to the main button.
In order to search for the "OK" text in a span, you need to use the node / period search. Which is why I did //*[contains(., 'OK')].

To find this button and then click on it, you would do the following

driver.find_element(By.XPATH, "//button[contains(@class, 'ant-btn-primary')]//*[contains(., 'OK')]/..").click()

ALTERNATE XPATH

//button[contains(@class, 'ant-btn-primary') and contains(., 'OK')]

And you would click on the button as such

driver.find_element(By.XPATH, "//button[contains(@class, 'ant-btn-primary') and contains(., 'OK')]").click()
like image 87
Zvjezdan Veselinovic Avatar answered Jul 22 '26 23:07

Zvjezdan Veselinovic