我在nodejs中编写了一个脚本,以便自动从联机目录中检索数据。我知道我从来没有这样做过,所以我选择了javascript,因为它是我每天都在使用的语言。
因此,我从上找到的几个技巧可以轻松地访问页面的dom组件。我找到并检索了所有必要的信息,唯一缺少的步骤是恢复到下一个页面的链接,除了在加载页面4秒后生成的链接,并且链接包含一个散列,因此这个步骤是不可避免的。
我想做的是在页面加载4-5秒后恢复dom,以便能够恢复链接。
我查看了互联网,并提出了使用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(函数(页){^) TypeError: ph.createPage不是一个函数
我要做的是做我想做的事的最佳方式吗?如果不是,最简单的方法是什么?如果是的话,我的错误从何而来?
发布于 2016-12-22 11:39:26
如果你不用使用幻影,你可以用噩梦来做。
它是一个很好的库来解决像你这样的问题,它使用电子作为网络浏览器,你可以运行它与或不显示窗口(你也可以打开开发者的工具,如谷歌Chrome)
如果您想要在没有图形界面的服务器上运行它,则它只有一个缺陷,您必须至少安装框架缓冲区。
梦魇有像等待(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 黑客行动愉快!
https://stackoverflow.com/questions/41281959
复制相似问题