Finding WebElements, best practices Finding WebElements, best practices selenium selenium

Finding WebElements, best practices


First off, there are no "best practices," just ones that work well in your particular context. Sorry, that's an old gripe of mine...

I wouldn't spend the effort for custom attributes unless you can't work with an existing approach. I prefer using existing locators (find logic) where possible.

Whenever possible, use ID attributes. If the page is valid HTML, then IDs are unique on the page. They're extraordinarily fast for resolution in every browser, and the UI can change dramatically but your script will still locate the element.

Sometimes IDs aren't the right choice. Dynamically generated IDs are almost always the wrong choice when you're working with something like a grid control. You rely on an id that is likely tied to the specific row position and then you're screwed if your row changes.

In some of these cases your devs can help you out by appending or prepending constant values to a dynamically generated ID value. ASP.NET Webforms does crazy stuff with dynamically generated values, so I've used a suffix to my advantage several times.

Link text, name attribute values, and CSS selectors (JQuery style) are great second choices when you can't get a stable, reliable ID, or one's just not available.

XPath is my last choice in nearly all situations. It's slow, can be extremely brittle, and is hard to deal with when it's a complex XPath. That said, if you need to move up and down the page DOM for your locators, then it's the only choice.

Using one of the existing FindBy methods means you'll be using a well-understood, well-supported locator strategy. That's a big bonus when you're trying to figure out an old test, or when onboarding someone new to your team.

That's my $0.02.


I think this will help Selenium Locators Best Practices

Tastiest Locators:IDNameClassLinkText or Partial Text

Yummy LocatorsIndexXPathChild ElementsCSS PropertiesEdible LocatorsJS EventsDOM ElementsKeyStrokesCoordinates


If I understood you correctly you can continue using @FindBy annotation with css selectors such as css = "[test='...']".