Reputation: 73
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
Upvotes: 7
Views: 4963
Reputation: 547
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()
Upvotes: 11
Reputation: 638
There should be no reason why driver.find_element_by_xpath('//span[text()="OK"]').click()
shouldn't work. Perhaps the page isn't fully loaded when you try to obtain the element via its xpath, and in that case, you'd have to wait until that elements load via WebDriverWait.
Upvotes: 1