package www.zr.com; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.events.AbstractWebDriverEventListener; public class zr_EventListener extends AbstractWebDriverEventListener { //表示需要侦听浏览器浏览到某个页面后触发的事件 @Override public void afterNavigateTo(String url,WebDriver driver) { System.out.printf("after Navigate To "+url); } //表示需要侦听浏览器回退浏览某个页面后触发的事件 @Override public void afterNavigateBack(WebDriver driver) { System.out.printf("after Navigate Back To "+driver.getCurrentUrl()); } //表示需要侦听鼠标单击页面上某个元素后触发的事件 @Override public void afterClickOn(WebElement webElement,WebDriver driver) { System.out.printf("after Click On "+webElement.getText()); } }
import org.openqa.selenium.support.events.EventFiringWebDriver; import www.zr.com.zr_EventListener; public class autorunner_test { public static void main (String [] args) { //测试网址 String url = "http://www.zr.com"; //Chromedriver.exe 文件地址 String Chromedriver_fileAddress = "C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe"; //设置环境变量 System.setProperty("webdriver.chrome.driver", Chromedriver_fileAddress); /******用固定端口打开应用************/ ChromeDriverService.Builder builder = new ChromeDriverService.Builder(); ChromeDriverService chromeService = builder.usingDriverExecutable(new File(Chromedriver_fileAddress)).usingPort(3333).build(); try{ chromeService.start(); }catch(IOException e){ e.printStackTrace(); } WebDriver xuyun_driver = new ChromeDriver(chromeService);
/******用固定端口打开应用************/
//侦听事件
EventFiringWebDriver eventFiringDriver = new EventFiringWebDriver(xuyun_driver);
zr_EventListener zrEventListener = new zr_EventListener(); eventFiringDriver.register(zrEventListener);
eventFiringDriver.get(url);
eventFiringDriver.findElement(By.id("personBtn")).click();
}
}
运行结果:
after Navigate To http://www.zr.com
after Click On 请登录