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



我在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'));

来自文档 (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.

因此,您需要直接调用等待回调或创建一个承诺:

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

我离开时承诺这样做,作为一项有待执行的工作。

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

webdriver.implicitly_wait(5);

最新更新