Multiple attribute XPath versus CSS locators

In a lot of situations, there is a need to include multiple attributes to make a locator unique, or work with multiple elements; XPath and CSS both have provisions to allow this. Let's take a look at some of those techniques:

  • Hierarchy: One mistake often made is including the entire hierarchy tree in a locator. The main problem with this is that if you use four to five levels of parenting, any time the style of the page changes, all the locators will be broken. The best practice to follow when using XPath and CSS is to include the element locator and, if necessary, one level of hierarchy only. This would include ancestor, descendant, preceding, following, preceding-sibling, and following-sibling.
  • Or conditions: When a common locator is different on some pages, users can "or" the locator to find the element by one method or the other. For example:
// Xpath
@FindBy(xpath = "//img[@src='myLogo.png' or @src='myLogo.svg']")

// css
@FindBy(css = "div[id*='progressBar'], a[id*='progressBar'], i[id*='progressBar']")
  • And conditions: When a common locator needs multiple methods to make it unique, users can "and" the locator to find the element by both methods. For example:
// Xpath
@FindBy(xpath = "//div[contains(@class,'header') and contains(text(),'label')]")

// css
@FindBy(css = "input[id*='email'][name='username']")
  • Parent, child, sibling, relatives: When there are many elements with the same ID, classes, or attributes, such as when there are duplicate buttons on the page, users can use one of the hierarchy methods to define the locators. Here are a couple of XPath code examples:
// ancestor
@FindBy(xpath = "//input[@id='myID']/ancestor::div/span")

// descendant
@FindBy(xpath = "//*[@id='myModal']/descendant::h2")

// following
@FindBy(xpath =
"//div[starts-with(text(),'title')]/following::i[@class='icon-close']")

// following-sibling
@FindBy(xpath = "//div[.='label']/following-sibling::div[@class='myGraphic']")

// preceding
@FindBy(xpath = "//a[contains(text(),'myID')]/preceding::input[@class='myCheckbox']")

// preceding-sibling
@FindBy(xpath = "//div[.='label']/preceding-sibling::div[@class='myGraphic']")
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.211.87