StaleElementReferenceError:过时的元素引用:元素未附加到页面文档

时间:2019-03-25 14:28:10

标签: javascript protractor

我已经在一个量角器页面中创建了一个函数。单击该功能后,我会转到我使用了require关键字的另一页。

this.naviagteToSwaggerOrReadme = function(str) {

  this.endpointDropdown.click();
  browser.sleep(2000);
  //element(by.partialLinkText('swagger/index.html')).click();
  element(
     by.className('popover ng-scope ng-isolate-scope bottom fade in')
  )
  .all(by.tagName('a')).then(function(obj) {

    console.log('Number of elements with the a tag in the parent element is ' + obj.length);

    for (let i = 0; i < obj.length; i++) {
      obj[i].getText().then(function(text) {
        console.log('The text on the link  is ' + text);
        var linkText = text;

        if (linkText.toLowerCase().indexOf(str) !== -1) {
          obj[i].click();
        } else {
          obj[i + 1].click();
        }
      })
    }

  });

  browser.sleep(5000);
  return require('./Swagger.js');
};

我正在调用相同的功能。

swagger = appsPageOne.naviagteToSwaggerOrReadme('swagger');
        swagger.getSwaggerTitle().then(function(title){
            console.log('This is the title '+title);
        })

但是我得到的错误是:

 Message:
    Failed: stale element reference: element is not attached to the page document
      (Session info: chrome=74.0.3729.6)
      (Driver info: chromedriver=2.46.628402 (536cd7adbad73a3783fdc2cab92ab2ba7ec361e1),platform=Windows NT 10.0.15063 x86_64)
  Stack:
    StaleElementReferenceError: stale element reference: element is not attached to the page document

1 个答案:

答案 0 :(得分:0)

  1. 通过element.all().getText()阅读所有找到的链接的文本
  2. 通过将链接的文本与参数str比较来找出匹配链接的索引:
  3. 再次搜索所有链接,然后通过element.all().get(index)单击匹配的链接
  4. return require('./Swagger.js');放入then()内,否则执行return语句,然后单击匹配的链接。

更改代码如下:

this.naviagteToSwaggerOrReadme = function(str) {

  this.endpointDropdown.click();
  browser.sleep(2000);

  let links = element.all(
     by.css('.popover.ng-scope.ng-isolate-scope.bottom.fade.in a')
  )

  return links.getText().then(function(txts) {

    let size = txts.length;

    console.log('Number of elements with the a tag in the parent element is ' + size);

    let index = txts.findIndex(function(txt){
      return txt.toLowerCase().includes(str);
    });

    if(index === -1) {
      index = size - 1;
    }

    links.get(index).click();
    browser.sleep(5000);

    return require('./Swagger.js');
  });

};

naviagteToSwaggerOrReadme()返回承诺,因此您需要在then()中使用返回的swagger

appsPageOne.naviagteToSwaggerOrReadme('swagger').then(function(swagger){
  swagger.getSwaggerTitle().then(function(title){
      console.log('This is the title '+title);
  });
});