在测试过程中,因为一切操作都是程序自动进行,有时候会很难看出来在操作哪个元素,或者在调试过程中也要查看具体操作的元素。因此,使用高亮显示被操作页面元素的方法,可以提示测试人员正常操作页面上的哪些元素,提高测试过程中的效率。
具体实例如下:
package cn.om.webdriverapi; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.AfterMethod; public class TestHighLightWebElement { WebDriver driver; String url; JavascriptExecutor jsExecutor; @Test public void testHighLightWebElement() { driver.get(url); jsExecutor=(JavascriptExecutor)driver; WebElement input = driver.findElement(By.id("query")); WebElement submitbut = driver.findElement(By.id("stb")); highlightElement(input); input.sendKeys("test"); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } returnNormal(input); highlightElement(submitbut); submitbut.click(); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } returnNormal(submitbut); } public void highlightElement(WebElement element) { jsExecutor.executeScript("arguments[0].setAttribute('style',arguments[1]);", element,"background:yellow;border:2px solid red"); } public void returnNormal(WebElement element){ jsExecutor.executeScript("arguments[0].removeAttribute('style');", element); } @BeforeMethod public void beforeMethod() { System.setProperty("webdriver.firefox.bin", "D:/Mozilla Firefox/firefox.exe"); driver = new FirefoxDriver(); url = "http://www.sogou.com"; } @AfterMethod public void afterMethod() { driver.quit(); } }