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,"");
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步