0

(I am a bit of a StackOverflow newbie, so please forgive any beginner mistakes and let me know what to improve in the future)

I am trying to select the highlighted button in the appended picture.

Problem:

  • There are many buttons of this kind all using the same description and XPath. So as far as I can tell there is no way of telling them apart by their cssSelector or XPath

Possible solution:

  • The h2 above the button contains a differentiable description of the button I need to select. So can I basically navigate to said h2 and then select the specific button belonging to it? -> How to code it? Are there easier ways to do this?

So far I know basic element selection as seen in this code sample:

    WebElement loginElement = driver.findElement(By.xpath("//*[@id='login-submitBtn']"));
    loginElement.click();

html sample

1
  • welcome to the community. You wrote good first question post here. Keep it up & accept answer which helped you. Happy teting! Commented Jan 25, 2023 at 12:55

1 Answer 1

0

Solution:

  • You can use different advance locator strategy using xpath which selenium supports. There would be many but mentioning few below:
  • Option 1: XPath using ‘AND’ & ‘OR’
    • The ‘AND’ & ‘OR’ operators in the XPath selector in Selenium are used when locating a WebElement based on certain condition sets
    • In the case of ‘AND,’ both the conditions should be True
    • On the other hand, either of the two conditions can be true for ‘OR’ in operator XPath
  • Option 2 : Relative locators if you are using Selenium 4

How to implement it?

  • Option 1:
    • Using AND
driver.findElement(By.xpath("//h2[@type='button' AND @name='select-organisation-button']"
  • Using Tag with Class, and Attribute value
driver.findElement(By.cssSelector("h2.MuiButton-text[name=\"select-organisation-button\"]"));
  • Option 2:
targetted_button_locator = locate_with(By.TAG_NAME, "h2").below({By.NAME: "select-organisation-button"})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.