在页面加载几秒后检索 html 页面内容

Retrieve html content of a page several seconds after it's loaded

我正在用 nodejs 编写脚本以自动从在线目录检索数据。 我知道我从来没有这样做过,所以我选择了 javascript 因为这是我每天都在使用的语言。

因此,我根据在 google 上找到的一些提示,将 request 与 cheerios 一起使用,以轻松访问页面 dom 的组件。 我找到并检索了所有必要的信息,唯一缺少的步骤是将 link 恢复到下一页,除了该页面是在加载页面后 4 秒生成的,并且 link 包含一个散列,因此步骤是不可避免的。

我想做的是在加载页面 4-5 秒后恢复 dom 页面,以便能够恢复 link

我在网上看了很多关于使用 PhantomJS 进行此操作的建议,但在使用 node 进行了多次尝试后我无法让它工作。

这是我的代码:

#!/usr/bin/env node
require('babel-register');
import request from 'request'
import cheerio from 'cheerio'
import phantom from 'node-phantom'

phantom.create(function(err,ph) {

  return ph.createPage(function(err,page) {

    return page.open(url, function(err,status) {

      console.log("opened site? ", status);
      page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function(err) {

        //jQuery Loaded.
        //Wait for a bit for AJAX content to load on the page. Here, we are waiting 5 seconds.

        setTimeout(function() {

          return page.evaluate(function() {

            var tt = cheerio.load($this.html())
            console.log(tt)

          }, function(err,result) {

            console.log(result);
            ph.exit();

          });

        }, 5000);

      });
    });
  });
});

但我收到此错误:

return ph.createPage(function (page) { ^

TypeError: ph.createPage is not a function

我将要做的是做我想做的最好的方式吗?如果不是,最简单的方法是什么?如果是这样,我的错误从何而来?

如果你不必使用 phantomjs 你可以使用 nightmare 来完成它。

这是一个非常简洁的库,可以解决像你这样的问题,它使用电子作为网络浏览器,你可以 运行 它显示或不显示 window (你也可以打开开发者工具,比如 Google Chrome)

如果你想在没有图形界面的服务器上运行它只有一个缺陷,你必须至少安装 framebuffer。

Nightmare 有类似 wait(cssSelector) 的方法,它会等到某些元素出现在网站上。

你的代码应该是这样的:

const Nightmare = require('nightmare');
const nightmare = Nightmare({
    show: true, // will show browser window
    openDevTools: true // will open dev tools in browser window 
});

const url = 'http://hakier.pl';
const selector = '#someElementSelectorWitchWillAppearAfterSomeDelay';

nightmare
        .goto(url)
        .wait(selector)
        .evaluate(selector => {
    return {
        nextPage: document.querySelector(selector).getAttribute('href')
    };
}, selector)
.then(extracted => {
    console.log(extracted.nextPage); //Your extracted data from evaluate
});
//this variable will be injected into evaluate callback
//it is required to inject required variables like this,
// because You have different - browser scope inside this
// callback and You will not has access to node.js variables not injected 

祝您黑客愉快!