在Node.js中使用selenium-webdriver执行“命令”的方法

10

我对通过javascript API执行一些高级“Commands”感兴趣:https://code.google.com/p/selenium/source/browse/javascript/webdriver/command.js

如果我从基本代码开始:

var browser = new webdriver
        .Builder()
        .usingServer(server.address())
        .withCapabilities(webdriver.Capabilities.phantomjs())
        .build();

我尝试过各种语法来执行“likely”的功能,但都失败了。例如:

// does not work
console.log(webdriver.Command('getWindowSize'))
// does not work
console.log(browser.Command('getWindowSize'))

有人知道如何在Selenium JavaScript WebDriver中执行"获取窗口大小"或"设置窗口大小"吗?


我没有使用过Command相关的东西,但我们已经使用ExecuteScript函数来执行JavaScript。如果我没记错的话,它会返回JavaScript通常返回的内容,所以只需执行一个返回窗口大小的JavaScript函数(我认为您可能需要分别获取宽度和高度,或者将它们分别作为两个值返回为一个对象之类的形式)。 - Pete
1
谢谢Pete。在那种情况下,console.log(browser.ExecuteScript('window.height'));似乎不起作用。console.log(browser.executor_.execute('window.height'));也不行。你有任何示例吗? - Alex C
2
Alex,我遇到了很多问题,和你遇到的类似。在Node.js中使用Selenium-webdriver非常混乱。整个Promise系统似乎有点讲得通,但我还没有找到实际可靠的例子(除了简单的“hello world”之外)来说明如何使用它。我已经尝试了一整天,只是想获取一个元素的可见文本...(叹气)我想我要放弃selenium-webdriver,改用http://www.webdriver.io/。看起来很有前途,并且似乎使用已经熟悉的链接语法来近似同步。 - rinogo
3个回答

28

你可能正在寻找 driver.executeScript

示例:

var driver = new webdriver.Builder().
   withCapabilities(webdriver.Capabilities.chrome()).
   build();

driver.executeScript('return 2').then(function(return_value) {
    console.log('returned ', return_value)
});

这将在控制台中记录2。

我还使用以下内容进行了测试:

driver.get('http://underscorejs.org/');

driver.executeScript('return _').then(function(return_value) {
    console.log('returned ', return_value)
});

...会正确地列出所有在_上定义的方法,因此它似乎可以工作。


1
我找到这个文档的时间比平常长了一点。http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/chrome_exports_Driver.html - Daniel Lizik

0
你需要使用driver.executeScript()。你可以传递一个函数或者一个字符串。
const _scraper = () => {
  return document.title;
}

const getPageTitle = async (url) => {
  await driver.get(url);
  const pageTitle = await driver.executeScript(_scraper);
  console.log(pageTitle);
}

你也可以向函数传递参数。

const _scraper1 = (arg) => {
  return document.getElementsByTagName(arg);
}

const getTagData = async (url) => {
  await driver.get(url);
  const metas = await driver.executeScript(_scraper, 'meta');
  console.log(metas);
}

0
在我的npm软件包中,有一个文件node_modules/selenium-webdriver/test/execute_script_test.js,其中有许多使用driver.executeScript的示例(在文件的最后,他们将execute定义为executeScript的别名)。

虽然链接到外部资源是可以的,但答案应该是自包含的,外部资源不应该是“严格”必要的,而是额外的内容(实际上,这个答案甚至没有包含该链接,只是提到了“我的npm包”)。 - Martin Tournoij
我的本意并不是回答这个问题。我觉得已经有人回答了。我想指出一个有用的、补充性的资源,这个资源在 selenium-webdriver 的 npm 模块中已经被安装了。 - AdamW
1
我现在明白了,我本应该将这个信息作为评论而不是回答添加。 - AdamW
https://github.com/SeleniumHQ/selenium/blob/trunk/javascript/node/selenium-webdriver/test/execute_script_test.js - Tom Howard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接