我正在努力获取文本框的实际文本,因为我需要将它作为文本存储在变量中而不是将它与值进行比较,因为我需要将它添加到 url 的末尾调用另一个页面。
我尝试使用 ebeal 建议的代码,但它没有达到我想要的效果:
var access_token = driver.findElement(webdriver.By.name("AccToken"))
.getAttribute("value")
.then(console.log);
// This outputs the right result but only to the console as I can't save it to a variable
var access_token = driver.findElement(webdriver.By.name("AccToken"))
.getText();
access_token = access_token.then(function(value){
console.log(value);
});
console.log("the new one : " + access_token);
// this one outputs : the new one: Promise::304 {[[PromiseStatus]]: "pending"}
有什么想法吗?
最佳答案
WebdriverJS 是纯异步的。这意味着,您需要提供一个回调并在回调中实例化您的变量,而不是简单地将调用函数的结果分配给您的变量。
这就是为什么每次您 console.log 您的 access_token 变量时,您总是会得到一个 promise 。 webdriverjs 文档稍微解释了 selenium-webdriver 中的 promise 如何工作 https://code.google.com/p/selenium/wiki/WebDriverJs#Understanding_the_API
您可以执行以下操作将文本分配给变量:
var access_token;
var promise = driver.findElement(webdriver.By.name("AccToken")).getText();
promise.then(function(text) {
access_token = text;
});
我强烈推荐 WebdriverIO,因为它消除了必须编写自己的 promise 的痛苦。 http://webdriver.io/
关于javascript - 如何在 selenium webdriver 中获取文本框的值,Js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31159675/