Highlight elements with Selenium WebDriver

Problem

We like to highlight elements with Selenium WebDriver like we could do with the previous version of Selenium. This will help us to see what is actually is going on in the browser. This method will slow down your tests a bit, but sometimes it is useful for debugging purpose.

 

Solution


public void highlightElement(WebDriver driver, WebElement element) {  
   for (int i = 0; i < 2; i++) {     
    JavascriptExecutor js = (JavascriptExecutor) driver;     
    js.executeScript("arguments[0].setAttribute('style', arguments[1]);",    
             element, "color: yellow; border: 2px solid yellow;");     
   js.executeScript("arguments[0].setAttribute('style', arguments[1]);",     
            element, "");     } } 

How to use it

 

@Test public void highlightTest() {  

WebElementsearchField=driver.findElement(By.cssSelector("input#search_query_top"));

highlightElement(searchField);searchField.sendKeys("ipod nano");

WebElementsearchButton=driver.findElement(By.cssSelector("input[name='submit_search']"));

highlightElement(searchButton);searchButton.click();

StringsearchHeader=driver.findElement(By.cssSelector("H1")).getText().toLowerCase();Assert.assertTrue(searchHeader.contains("ipod nano"));

}

publicvoidhighlightElement(WebElementelement){

for(inti=0;i<2;i++){

JavascriptExecutorjs=(JavascriptExecutor)driver;

js.executeScript("arguments[0].setAttribute('style', arguments[1]);",element,"color: yellow; border: 2px solid yellow;");

js.executeScript("arguments[0].setAttribute('style', arguments[1]);",element,"");

}

}

 

 

 

 

 

 

posted @ 2012-08-22 15:40  布瓜  阅读(595)  评论(0编辑  收藏  举报