What is the best way to detect an element on a webpage for automated testing using SeleniumRC using Java?. I know that there are XPath ele开发者_开发知识库ments and CSS elements, but which one is best?
thanks! Nitin
X-Paths are accurate, indeed. However, they are also very fragile. Any change to the website that moves things around has the potential of breaking your tests. IDs are by far the least fragile, since it doesn't matter if your changes to a , your tests will always find it.
In my opinion, the most accurate way is XPath as you can use XPath's to describe the exact position of an element within the DOM, however there are some instances where CSS locators work better than XPaths.
Using selenium's ID locator is the most simple, but unless the element you are looking for has an ID not always useful.
The biggest negative when using XPath's is the performance with Selenium RC and browsers with bad JavaScript rendering engines (Think IE6/IE7). Quite a bit of work has been dome to try and rectify this so if you use well formed XPath's that only search specific parts of the DOM this problem should be minimal. The Selenium webdriver implementation is much faster.
The summary is really there is no one answer it depends what you want out of a locator, and which browsers you are testing. I personally use XPath in 99% of instances.
I personally use XPath almost exclusively with the occasional CSS locator.
CSS selectors are faster but not always available; You can always rely on XPath but could take a toll on performance.
Xpath is the way I've used. It will help if your nodes have unique id's.
The best and fastest way to find an element is by id. In many browsers, the time to find an element by it's id is linear or even constant. very fast.
For example, given an element defined as:
<input type="text" name="passwd" id="passwd-id" />
You should find it like this:
selenium.type("passwd-id", "test");
Or if you're using the webdriver API:
element = driver.findElement(By.id("passwd-id"));
If the elements on your pages don't have ids, add them! or ask the developers to add them!
The next best way to find elements is by name. That's pretty quick as well, especially if the name is unique on the page.
For example:
selenium.type("passwd", "test");
Or if you're using the webdriver API:
element = driver.findElement(By.name("passwd"));
The third way of finding an element is using CSS selectors. Modern browsers are very good at locating elements this way.
The worst way to locate an element is using xpath. xpath is slow and brittle and hard to read.
Simon Stewart, a major contributor to Selenium, answers this question here: http://www.youtube.com/watch?v=oX-0Mt5zju0&feature=related look for timestamp 39:00
There's also good info here: http://seleniumhq.org/docs/02_selenium_ide.html#locating-elements
精彩评论