javascript - 从 WebDriverJS 确定 session ID

标签 javascript node.js selenium webdriver

我正在尝试在浏览器上运行 WebDriverJS,但文档对如何让它控制主机浏览器有些含糊。在这里,它说:

Launching a browser to run a WebDriver test against another browser is a tad redundant (compared to simply using node). Instead, using WebDriverJS in the browser is intended for automating the browser actually running the script. This can be accomplished as long as the > URL for the server and session ID for the browser are known. While these values may be passed to the builder directly, they may also be defined using the wdurl and wdsid "environment variables", which are parsed from the loading page's URL query data:

    <!-- Assuming HTML URL is /test.html?wdurl=http://localhost:4444/wd/hub&wdsid=foo1234 -->
    <!DOCTYPE html>
    <script src="webdriver.js"></script>
    <input id="input" type="text"/>
    <script>
      // Attaches to the server and session controlling this browser.
      var driver = new webdriver.Builder().build();

      var input = driver.findElement(webdriver.By.tagName('input'));
      input.sendKeys('foo bar baz').then(function() {
        assertEquals('foo bar baz',
            document.getElementById('input').value);
      });
    </script>

我想从 Node.js 打开我的测试页面,然后运行客户端脚本中包含的命令。但是,我不知道如何在构建 session 时提取 session ID(wdsid 查询参数)。有人知道吗?

最佳答案

经过大量实验和阅读 WebDriverJS 源代码后终于弄明白了。

var webdriver = require('./assets/webdriver');

var driver = new webdriver.Builder().
    usingServer('http://localhost:4444/wd/hub').
    withCapabilities({
        'browserName': 'chrome',
        'version': '',
        'platform': 'ANY',
        'javascriptEnabled': true
    }).
    build();

var testUrl = 'http://localhost:3000/test',
    hubUrl = 'http://localhost:4444/wd/hub',
    sessionId;

driver.session_.then(function(sessionData) {
    sessionId = sessionData.id;
    driver.get(testUrl + '?wdurl=' + hubUrl + '&wdsid=' + sessionId);
});

driver.session_ 返回一个 Promise 对象,该对象在实例化时将包含 session 数据和其他信息。使用 .then(callback(sessionData)) 将允许您根据需要操作数据。

关于javascript - 从 WebDriverJS 确定 session ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11196751/

相关文章:

javascript - 如何使 div 居中并与其嵌套的 float div 保持对齐?

javascript - JQuery - 将 li a 的 href 更改为 javascript :void(0)

javascript - 有没有办法在 javascript 文件中要求 typescript 文件?

selenium - 验证文本是否存在于特定元素中

python - 如何使用 selenium python 检索元素的所有 css 属性?

javascript - aframe:如何从 Canvas 中获取像素

javascript - 如何减少这个脚本

javascript - 具有响应和 http 方法的 Node JS 变量范围

javascript - expressjs : get requested url

selenium - 如何通过 Java 使用 XPath 和 Selenium WebDriver 单击 SVG 元素