黄瓜木偶-尝试滚动以使元素可见-滚动不起作用

时间:2020-06-12 15:09:12

标签: scroll cucumber puppeteer

这在一个黄瓜木偶项目的world.js中。

我意识到我想使用querySelector查找的元素最初不在屏幕上,因此我想向右滚动。

因此我添加了滚动代码,但屏幕截图显示未发生滚动。 它还显示滚动条是可见的。

async getForecastStartColumn(selector, attribute, wait = 0) {
      let forecast;
      await this.page.waitFor(wait);

      await this.page.evaluate(_ => {
         window.scrollBy(3000, 0);
      });

      await this.page.waitFor(1000);
      await this.page.screenshot({ path: './world-177.png', fullPage: true });
      result = await this.page.document.querySelector('div[class="ag-header-cell ag-header-cell-sortable 
          grid-column-header-forecast"]');
   }

//rest of code omitted

1 个答案:

答案 0 :(得分:1)

尝试使用此代码向右滚动。

const left = $(document).outerWidth() - $(window).width();
$('body, html').scrollLeft(left);

async getForecastStartColumn(selector, attribute, wait = 0) {
      let forecast;
      await this.page.waitFor(wait);

      await this.page.evaluate(_ => {
         const left = $(document).outerWidth() - $(window).width();
         $('body, html').scrollLeft(left);
      });

      await this.page.waitFor(1000);
      await this.page.screenshot({ path: './world-177.png', fullPage: true });
      result = await this.page.document.querySelector('div[class="ag-header-cell ag-header-cell-sortable 
          grid-column-header-forecast"]');
   }

//rest of code omitted

编辑1

我使用的是纯js,而不是jQuery。您应该知道向右滚动的元素,并使用该元素的选择器替换 'html'可以向右滚动。

我正在使用.scrollTo(xpos, ypos)可以向左,向右,顶部和按钮滚动。 docs。并使用.scrollWidth,这是元素内容的宽度(以像素为单位)。 docs。并使用.pageYOffset获取元素的当前y偏移量,以在滚动过程中保持此位置。因为.scrollTo(xpos, ypos)需要xy。我们只需要更改xpos并保持ypos的值即可。 docs

async getForecastStartColumn(selector, attribute, wait = 0) {
      let forecast;
      await this.page.waitFor(wait);

      await this.page.evaluate(_ => {
         const terget = document.querySelector('html');
         terget.scrollTo(terget.scrollWidth, terget.pageYOffset);
      });

      await this.page.waitFor(1000);
      await this.page.screenshot({ path: './world-177.png', fullPage: true });
      result = await this.page.document.querySelector('div[class="ag-header-cell ag-header-cell-sortable 
          grid-column-header-forecast"]');
   }

//rest of code omitted