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

我在nodejs中编写脚本来自动从联机目录中检索数据。 知道我从来没有这样做,我select了JavaScript,因为它是我每天使用的语言。

因此,我从几个技巧,我可以find在谷歌使用请求与cheerios轻松访问页面的dom组件。 我发现并检索了所有必要的信息,唯一缺less的步骤是恢复到下一个页面的链接,除了在页面加载4秒后生成一个链接并且链接包含散列以便这一步骤是不可避免的。

我想要做的是在加载后4-5秒钟恢复dom,以便能够恢复链接

我在网上看了一下,还有很多build议使用PhantomJS进行这个操作,但是经过多次尝试后,我无法让它工作。

这是我的代码:

#!/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); }); }); }); }); 

但我得到这个错误:

返回ph.createPage(function(page){^

TypeError:ph.createPage不是一个函数

我所要做的是做我想做的最好的方式? 如果不是最简单的方法是什么? 如果是这样,我的错误从哪里来?

如果你不必使用phantomjs你可以使用噩梦来做到这一点。

这是相当整洁的图书馆来解决像你这样的问题,它使用电子作为网页浏览器,你可以运行它有或没有显示窗口(你也可以像Google Chrome一样打开开发者工具)

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

梦魇有一种方法就是等待(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 

快乐的黑客!