简体   繁体   English

在 javascript 中使用 Selenium 驱动程序获取 WebElement 文本内容

[英]Get WebElement text content with Selenium Driver in javascript

I would like to check if the element I retrieved using its id contains the expected text value.我想检查我使用其id检索的元素是否包含预期的文本值。

var driver = require('selenium-webdriver');
var By = driver.By;

var elem = this.driver.findElement(By.id('my_id'));
assert.equal(elem.getText(), 'blablabla');

Unfortunately this isn't the way to go:不幸的是,这不是要走的路:

 AssertionError: ManagedPromise {
   flow_:
    ControlFlow {
      propagateUnhandledRejections_: true,
      activeQueue_:
       TaskQueue {
      == 'blablabla'

I can't manage to find an example how to do this simple check.我无法找到如何进行这个简单检查的示例。

The reason for that is that elem.getText() is actually a Promise .原因是 elem.getText() 实际上是一个Promise That means, that it will be executed asynchronously, and it's result will be available at a later point in time.这意味着,它将异步执行,并且它的结果将在稍后的时间点可用。 The return value of getText() is not the actual text, but a pointer to that asynchronous execution. getText() 的返回值不是实际的文本,而是指向异步执行的指针。

To actually use the return value of getText() (once it has been computed), use the then method and pass it a function.要实际使用 getText() 的返回值(一旦计算完成),请使用then方法并向其传递一个函数。 This anonymous function will then get called once the text has been computed, and you can work with it (for instance, assert that it is equal to an expected value):一旦文本被计算出来,这个匿名函数就会被调用,你可以使用它(例如,断言它等于预期值):

var elem = driver.findElement(By.id('mydiv'));
elem.getText().then(function(s) {
  assert.equal(s, "content");
});

Or, if you prefer the use of lambda expressions :或者,如果您更喜欢使用lambda 表达式

elem.getText().then(s => assert.equal(s, "content"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM