Add a new WebElement selection strategy to Selenium 2 by extending the By class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public class ByJQuerySelector extends By { private final String jQuerySelector; public ByJQuerySelector(String selector) { this .jQuerySelector = selector; } @Override public List findElements(SearchContext context) { //TODO:Implement return null ; } @Override public WebElement findElement(SearchContext context) { return (RemoteWebElement) ((JavascriptExecutor) context) .executeScript( "return $('" + jQuerySelector+ "').get(0);" ); } @Override public String toString() { return "By.jQuerySelector: " + jQuerySelector; } } |
Now you can select a WebElement with a JQuery selector.
1 2 3 4 5 6 7 8 9 10 11 | @Test public void example6(){ //Now I can use JQuery selectors to find elements on the page! By loc = new ByJQuerySelector( "a[title=Sign In]" ); driver.findElement(loc).click(); assertEquals( "O2 - Sign in - View bills , balances and emails in your My O2 account:" ,driver.getTitle()); } |
Today’s blog post is from O2 Broadband. Special thanks for their support.
Reference