我正在寻找一个请求网页的示例,等待JavaScript呈现(JavaScript修改DOM),然后获取页面的超文本标记语言。
这应该是一个简单的例子,有一个明显的PhantomJS用例。我找不到一个像样的例子,文档似乎都是关于命令行的使用。
发布于 2016-03-16 02:26:59
使用phantomjs-node
的v2,可以很容易地在处理后打印HTML。
var phantom = require('phantom');
phantom.create().then(function(ph) {
ph.createPage().then(function(page) {
page.open('https://stackoverflow.com/').then(function(status) {
console.log(status);
page.property('content').then(function(content) {
console.log(content);
page.close();
ph.exit();
});
});
});
});
这将显示与使用浏览器呈现的输出相同的输出。
编辑2019:
您可以使用async/await
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);
});
const status = await page.open('https://stackoverflow.com/');
const content = await page.property('content');
console.log(content);
await instance.exit();
})();
或者,如果你只是想测试,你可以使用npx
npx phantom@latest https://stackoverflow.com/
发布于 2012-06-01 04:21:08
我在过去使用了两种不同的方法,包括查询Declan提到的DOM的page.evaluate()方法。我从网页传递信息的另一种方式是将信息从那里传递给console.log(),并在phantomjs脚本中使用:
page.onConsoleMessage = function (msg, line, source) {
console.log('console [' +source +':' +line +']> ' +msg);
}
我可能还会在onConsoleMessage中捕获变量msg并搜索一些封装的数据。取决于您希望如何使用输出。
然后在Nodejs脚本中,您必须扫描Phantomjs脚本的输出:
var yourfunc = function(...params...) {
var phantom = spawn('phantomjs', [...args]);
phantom.stdout.setEncoding('utf8');
phantom.stdout.on('data', function(data) {
//parse or echo data
var str_phantom_output = data.toString();
// The above will get triggered one or more times, so you'll need to
// add code to parse for whatever info you're expecting from the browser
});
phantom.stderr.on('data', function(data) {
// do something with error data
});
phantom.on('exit', function(code) {
if (code !== 0) {
// console.log('phantomjs exited with code ' +code);
} else {
// clean exit: do something else such as a passed-in callback
}
});
}
希望这能对你有所帮助。
发布于 2013-12-19 00:07:38
为什么不直接用这个呢?
var page = require('webpage').create();
page.open("http://example.com", function (status)
{
if (status !== 'success')
{
console.log('FAIL to load the address');
}
else
{
console.log('Success in fetching the page');
console.log(page.content);
}
phantom.exit();
});
https://stackoverflow.com/questions/9966826
复制相似问题