1

On a external website I am trying to click the save button. But a cancel button has the same class.

buttonSave = browser.find_element_by_class_name("_spectrum-Button_7a745")
buttonSave.click()

HTML :

<button class="_spectrum-Button_7a745 _spectrum-Button--secondary_7a745 _spectrum-ButtonGroup-Button_25328" type="button" data-testid="cancel-button">
  <span class="_spectrum-Button-label_7a745">Cancel</span>
</button>
<span class="_spectrum-Button-label_7a745">Cancel</span>

<button class="_spectrum-Button_7a745 _spectrum-Button--cta_7a745 _spectrum-ButtonGroup-Button_25328" type="button" data-testid="cta-button">
  <span class="_spectrum-Button-label_7a745">Save</span>
</button>
<span class="_spectrum-Button-label_7a745">Save</span>
Olaf Kock
  • 46,930
  • 8
  • 59
  • 90
Reventlow
  • 147
  • 1
  • 10
  • I've inserted linebreaks in your HTML code - are you sure that there are two of the same labels for each button? – Olaf Kock Sep 03 '21 at 07:38

1 Answers1

2

In this case you can apply text based xpath.

//span[text()='Save']/parent::button

There are basically two save text on the HTML that you've shared. So, when we just write text based xpath which is //span[text()='Save'] we still will be left out with two nodes. so to further distinguish, we have to use parent node which is a button so, that is the reason we are using parent::button

PS: text based xpath should only be used when the Automation Engineer knows, the website is going to be in a particular language. in this case for e.g. English.

Also in case you are looking for css_selector, the below should get the job done.

button[data-testid='cta-button']

Code using xpath :

buttonSave = browser.find_element_by_xpath("//span[text()='Save']/parent::button")
buttonSave.click()

Code using css_selector :

buttonSave = browser.find_element_by_css_selector("button[data-testid='cta-button']")
buttonSave.click()
cruisepandey
  • 28,520
  • 6
  • 20
  • 38