一、为什么要让元素高亮显示?
为了更准确的显示查找到的元素,可以让元素高亮显示。
二、如何实现?
public class TestGaoLiang { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS); driver.get("http://www.baidu.com"); WebElement oEdit = driver.findElement(By.name("wd")); highlightElement(driver, oEdit); WebElement oButton = driver.findElement(By.id("su")); highlightElement(driver, oButton); driver.quit(); } public static void highlightElement(WebDriver driver, WebElement element) throws InterruptedException { JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("element = arguments[0];" + "original_style = element.getAttribute('style');" + "element.setAttribute('style', original_style + ";" // 背景色为黄色;红色加粗边框显示。 + "background: yellow; border: 2px solid red;");" // 高亮显示3s + "setTimeout(function(){element.setAttribute('style', original_style);}, 10000);", element); Thread.sleep(10000); } }
三、效果