Saturday, June 25, 2011

From Brittle XPath to CSS-selector

Use of xPath has taught me something valuable.... it is brittle!

So, with WebDriver, there are a few better ways to getting to certain elements or texts on a page:

Following our example site, on the this page we want to return a certain text.
"Etsy is more than a marketplace"

Here is a way to take your xPath and turn it into a more programmatic approach.

xpath on its own

//p[@class = 'quiet loud" and contains (text(), Etsy is more than a marketplace")]

By.cssSelector and Java or Groovy
findElement(By.cssSelector("p.quiet").getText().equals("Etsy is more than a marketplace")

One of the ways of finding the cssSelector in the page is with firebug, when you click on the element that you are trying to target a panel on the top of firebug will display the cssSelector.



1 comment:

  1. Paul,
    I am automating using Selenium with python and doing very similar things you are doing here. I have an interview with you guys next Wednesday. I would like to share a couple of pdf's that have really helped me identify objects using CSS And Xpath:

    Both can be found here, just click on the pdf to save and magnify it to make it useful.

    http://www.simple-talk.com/dotnet/.net-framework/xpath,-css,-dom-and-selenium-the-rosetta-stone/

    ReplyDelete