【问题标题】:Node js and Phantom jsNode js 和 Phantom js
【发布时间】:2018-06-13 20:09:17
【问题描述】:

我正在寻找一个页面作为学习 phantomjs 的练习,但是我目前遇到了一个问题。图像加载被推迟,所以我试图弄清楚如何让 phantom js 向下滚动并等待图像加载。滚动到页面底部不起作用,所以我想每 3 秒滚动 100 像素,直到它到达页面底部。我将如何实现这一目标?

const phantom = require('phantom');

(async function() {

  const instance = await phantom.create();
  const page = await instance.createPage();

  await page.on('onResourceRequested', function(requestData) {
    console.info('Requesting', requestData.url);
  });

  await page.open(<URL>);

  const js = await page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js');

  const data = await page.evaluate(function() {
    // Do something
  });

  page.render('test.pdf');  

  await page.close();
  await instance.exit();
})();

【问题讨论】:

  • 我认为这是不可能的,因为 phantomjs 没有滚动。渲染通常是整个页面。因此,要么是页面上的错误,要么您必须以某种方式为每个图像手动触发加载。

标签: javascript jquery node.js phantomjs phantomjs-node


【解决方案1】:

PhantomJS 确实支持“滚动”,有一个页面属性scrollPosition 大概可以这样使用:

await page.property('scrollPosition', { top: 300, left: 0 });

您可以动态更改scrollPosition,并在一段时间内增加它,这应该会触发负责图像加载的回调。

这里是原始 PhantomJS 脚本中的 an example,展示了沿着 Twitter 时间线走下去的技术。

【讨论】:

  • 我最终将它与一个向下滚动直到到达页面底部的等待功能结合使用。
  • @ElmosGotAGun 你能告诉我怎么做吗?它对我不起作用
【解决方案2】:

您也可以使用基于 phantom.js 的 node-webshot 来渲染 pdf。它有很多配置。您需要的是 renderDelay 来延迟截屏和 shotOffset 来滚动到您想要的位置。

【讨论】:

    【解决方案3】:
    const phantom = require('phantom');
    
    // Scrolls the page till new content is available
    async function scrollPage(page) {
        const currentContentLength = (await page.property('content')).length;
        await page.evaluate(function () {
            window.document.body.scrollTop = document.body.scrollHeight;
        });
        await wait(Math.max(5000, 10000 * Math.random()));
        const nextContentLength = (await page.property('content')).length;
        if (currentContentLength != nextContentLength) {
            console.log("Scrolling page:", await page.property('url'), "for more content");
            await scrollPage(page);
        }
    }
    
    // Scrolls the page and gets the page content using PhantomJS
    async function getPageData(pageUrl, shouldScrollPage) {
        const instance = await phantom.create();
        const page = await instance.createPage();
        await page.open(pageUrl);
        if (shouldScrollPage) {
            await scrollPage(page);
        }
        const pageContent = await page.property('content');
        await page.close();
        await instance.exit();
        return pageContent;
    };
    

    【讨论】:

      猜你喜欢
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 2017-09-24
      相关资源
      最近更新 更多