[Java][Selenium] How do I find and send clicks to a button that has the same name as other buttons in the frontend

Viewed 25

I'm currently working on a test suite and upon F12 and inspecting elements, I have several buttons that do not have id, have the same name, they are under the same class and the only thing different is the link to the page that they take you to.

Is there any way I can tell my webdrive to pick my specific button based on the link/ahref of the button?

If the question seems to be newbie please excuse me, it's only been 3 weeks since I started writing test suites in Selenium.

1 Answers

You can locate elements by XPath or by CSS Selector based on any combination of any attributes. Also it can contain dependency to some parent element(s).
For example if your buttons HTMLs are looking like this:

<button class="button" href="link1">
<button class="button" href="link2">
<button class="button" href="link3">

You can use the following XPaths

//button[@hef='link1']
//button[@hef='link2']
//button[@hef='link3']

Or CSS selectors

button[href='link1']
button[href='link2']
button[href='link3']

In case the href attribute values are very long or partially changing you still can create locators based or partially values, like the following
XPaths

//button[contains(@hef,'link1')]
//button[contains(@hef,'link2')]
//button[contains(@hef,'link3')]

Or CSS selectors

button[href*='link1']
button[href*='link2']
button[href*='link3']
Related