How to combine Selenium Locators

2,684 views
Skip to first unread message

Jerry Jaskierny

unread,
May 5, 2011, 5:56:54 PM5/5/11
to Selenium Users
I keep a library of all the Selenium locators in an application I
frequently test. Sometimes, I would like to reference an element on
the DOM that doesn't already exist in the library...but a parent for
the element already exists. A contrived example might be something
like...

// This would be in the library.
By resultListElement = By.xpath("/html/body/div[@class='header']/
div[@class='menu']/ul");


// This would be in another class, but it produces the
// string "By.xpath: By.xpath: /html/body/div[@class='header']/
div[@class='menu']/ul/li[1]".
WebElement firstResultInList = driver.resultListElement + "/li[1]";


Unfortunately, because By.toString() has been overridden, this is not
possible. So I'm currently forced to reduplicate existing locators.
Any suggestions on this?

Luke Inman-Semerau

unread,
May 5, 2011, 6:25:27 PM5/5/11
to seleniu...@googlegroups.com
This sounds kind of weird... Do you have a predefined set of static By's or something?

If you already have the WebElement from the original By, you can find other elements based off that element:

WebElement unorderedList = driver.findElementBy(By.xpath("//div[@class='header']/div[@class='menu']/ul"));
WebElement firstListItem = unorderedList.findElementBy(By.tagName("li"));  (or By.xpath, By.css, etc.)

-Luke


--
You received this message because you are subscribed to the Google Groups "Selenium Users" group.
To post to this group, send email to seleniu...@googlegroups.com.
To unsubscribe from this group, send email to selenium-user...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/selenium-users?hl=en.


Jerry Jaskierny

unread,
May 6, 2011, 11:58:29 AM5/6/11
to Selenium Users
Yep. It cuts down on a tremendous amount of work of creating initial
Xpath expressions and it's less error-prone when creating tests.

This isn't as convenient as I was hoping for, but it matches my
description. Thanks Luke!

Luke Inman-Semerau

unread,
May 6, 2011, 12:05:53 PM5/6/11
to seleniu...@googlegroups.com
Ah, you guys didn't choose to keep the XPaths in a property file or static strings? ~ could have done what you wanted there and then just manipulated the string as you want.

Personally that's not how my tests are organized... if there's a common component on the pages, then we'll have a static method or helper utility to get that element / validate it.

Good luck either way :)
Reply all
Reply to author
Forward
0 new messages