Задача: с помощью PhantomJS получить данные со страницы.
Что получилось сделать (см код ниже): получается загрузить страницу, получить нужные данные, записать их в файл json
Нужно после записи первой партии сделать нажатие на кнопку с #btn и повторить парс элементов $('#tab-1 .produkt-result').find('.col-item'), когда подгрузятся новые. Как это сделать?
'use strict';
var page = require('webpage').create();
var fs = require('fs');
var path = 'output.json';
var content = '';
page.settings.loadImages = false;
page.settings.resourceTimeout = 20000;
page.settings.userAgent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36';
page.open('http:/localhost/productsearch?searchTerm=&page=1', function (status) {
page.viewportSize = { width: 1024, height: 900 };
page.injectJs('http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js');
if (status !== "success") {
console.log("Unable to access network");
phantom.exit();
} else {
setTimeout(function() {
var news = page.evaluate(function() {
var _news = {};
$('#tab-1 .produkt-result').find('.col-item').each(function(i, value) {
var link = $(this).find('a');
var title = $.trim($(this).find('h3').text());
var url = $.trim(link.attr('href'));
var desc = $.trim($(this).find('.desc').text());
var img = $(this).find('img').attr('src');
var product_id = $(this).find('.icon-heart').data('product');
_news[i] = {
title: title,
url: url,
desc: desc,
img: img,
product_id: product_id
};
});
return _news;
});
console.log(JSON.stringify(news));
content = JSON.stringify(news);
fs.write(path, content, 'w');
phantom.exit();
}, 3000);
}
});
page.onInitialized = function(){
page.evaluate(function(){
var isFunction = function(o) {
return typeof o == 'function';
};
var bind,
slice = [].slice,
proto = Function.prototype,
featureMap;
featureMap = {
'function-bind': 'bind'
};
function has(feature) {
var prop = featureMap[feature];
return isFunction(proto[prop]);
}
// check for missing features
if (!has('function-bind')) {
// adapted from Mozilla Developer Network example at
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
bind = function bind(obj) {
var args = slice.call(arguments, 1),
self = this,
nop = function() {
},
bound = function() {
return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments)));
};
nop.prototype = this.prototype || {}; // Firefox cries sometimes if prototype is undefined
bound.prototype = new nop();
return bound;
};
proto.bind = bind;
}
});
};