简体   繁体   English

Selenium WebDriver页面事件侦听

[英]Selenium WebDriver Page Event Listening

I am using the java selenium webdriver to create some web tests but the pages I must test are for the most part dynamically loaded. 我正在使用java selenium Webdriver创建一些Web测试,但是我必须测试的页面大部分是动态加载的。 Luckily, events are triggered when certain content is loaded on the webpage. 幸运的是,当某些内容加载到网页上时会触发事件。

I would like to detect these events using selenium webdriver but I do not think it is natively possible. 我想使用Selenium Webdriver来检测这些事件,但是我认为这是不可能的。 I have checked out the doc for the EventFiringWebDriver but this looks like it will only work on selenium created events. 我已经签出了EventFiringWebDriver的文档,但这看起来仅适用于硒创建的事件。

Should I make use of implicit waits instead? 我应该改用隐式等待吗?

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

implicitlyWait means the driver will try to locate the element up to the specified amount of time, 10 seconds in your example. implicitlyWait意味着driver将尝试在指定的时间量内定位元素,在您的示例中为10秒。 It is always good idea to add it and you only need to do it once for each WebDriver instance. 添加它始终是个好主意,并且每个WebDriver实例只需执行一次。

WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Note that implicitlyWait will make sure the element exists in the DOM. 请注意, implicitlyWait将确保该元素存在于DOM中。 If you need to interact with the element it might not be good enough, you need the element to be visible. 如果您需要与该元素进行交互,这可能还不够好,那么您需要使该元素可见。 In those cases you can use explicit wait with Expected Conditions 在这些情况下,您可以对预期条件使用显式等待

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("id")));
// do something with the element

This will wait up to the specified amount of time to the element to be visible and will return the element just like driver.findElement . 这将等待指定时间,直到该元素可见 ,并将返回元素,就像driver.findElement一样。 The wait object can be set one time, but the second line needs to be called each time you want to wait for a condition. 可以将wait对象设置一次,但是每次要等待条件时都需要调用第二行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM