为什么Selenium WebDriver在页面未加载时解析了get()的承诺

时间:2017-05-26 15:55:05

标签: javascript selenium

我在版本3.4.0中使用selenium-webdriver。即使Chrome无法加载页面,下面的代码也会打印成功,因为端口3333上的服务器侦听尚未启动。

const selenium = require('selenium-webdriver');
const webdriver = new selenium.Builder().forBrowser('chrome').build();
webdriver.get('http://localhost:3333').then(() => console.log('success'));

2 个答案:

答案 0 :(得分:1)

从文档(http://www.seleniumhq.org/docs/03_webdriver.jsp#selenium-webdriver-api-commands-and-operations):

Dependent on several factors, including the OS/Browser combination,
WebDriver may or may not wait for the page to load. In some 
circumstances, WebDriver may return control before the page has
finished, or even started, loading. To ensure robustness, you need to wait
for the element(s) to exist in the page using Explicit and Implicit Waits.

因此,您需要直接调用wait回调或创建一个承诺来执行此操作:

webdriver.wait(function() {
    webdriver.get('http://localhost:3333').then(() => console.log('success'));
}, timeout);

我承诺将这样做作为一项练习来实施。

答案 1 :(得分:-1)

设置等待时间,如5秒钟,以加载页面或启动服务器。

webdriver.implicitly_wait(5);