如何在硒网络驱动程序Js中获取文本框的值

How to get value of textbox in selenium webdriver , Js

本文关键字:取文本 获取 Js 网络 驱动程序      更新时间:2023-09-26

我很难获得文本框的实际文本,因为我需要将其作为文本存储在变量中,而不是将其与值进行比较,因为我必须将其添加到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纯粹是异步的。也就是说,你需要提供一个回调并在回调中实例化你的变量,而不是简单地将函数的结果分配给你的变量。

这就是为什么你每次安慰都会得到一个承诺。记录你的access_token变量。webdriverjs文档解释了promise在selenium webdriver中的工作原理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,因为它可以减轻你自己写承诺的痛苦。http://webdriver.io/

所以这是我必须通过艰苦的方式学习的一件事,所以我希望这能有所帮助:

var access_token = await driver.findElement(webdriver.By.name("AccToken"))
    .getAttribute("value")
    .then((value) => { return value; });

我不确定您使用的是哪个版本的Webdriver,但使用WebdriverIO可能会有一些运气。特别是它的getText((函数,它将返回一个带有文本的回调,以便您可以在其他地方使用它。

http://webdriver.io/api/property/getText.html

client.getText('#elem').then(function(text) {
    console.log(text);
});

如果您只想获得值,这应该很好。如果您正在使用新的等待ES6语法;那么";承诺。

const { Builder, By, Key, until } = require('selenium-webdriver');
const assert = require('assert');
    
let access_token = await driver.findElement(By.name("AccToken")).getAttribute("value");

然后你甚至可以断言:

assert.equal(access_token, "your token value here");

有关硒网络驱动程序的更多信息,请参阅文档。请仔细查看Webdriver实例方法以获得更详细的信息。祝你好运