Это часть кода, которая является проблематической:
var obj = {};
function putInObject() {
obj.title = document.querySelector('[itemprop="title"]').innerText;
obj.description = document.querySelector('[itemprop="description"]').innerText;
}
casper.then(function(){
casper.wait(1000,function(){
links = this.evaluate(getItemLinks);
casper.each(links, function(self, link) {
self.thenOpen(link, function() {
this.echo(this.getTitle());
this.wait(7000, function(){
console.log("**************** \n WebPage is loaded \n ****************");
// Appearantly, The putInObject() doesn't run and "obj" remains null
casper.evaluate(putInObject);
this.echo(obj);
});
});
});
});
});
putInObject()
не запускается, даже я заменил casper.evaluate(putInObject);
с этим:
this.evaluate(function() {
obj.title = document.querySelector('[itemprop="title"]').innerText;
obj.description = document.querySelector('[itemprop="description"]').innerText;
});
Но это тоже не сработало, и obj печатается на консоль, например [object Object]
.
this.echo(this.getTitle());
однако работает отлично и печатает название страницы в консоли.
Это журнал вышеприведенного кода:
[debug] [phantom] opening url: https://example.com/category/section/, HTTP GET
[debug] [phantom] Navigation requested: url=https://example.com/category/section/, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] url changed to "https://example.com/category/section/"
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=https://staticxx.facebook.com/connect/xd_arbiter/r/0F7S7QWJ0Ac.js?version=42#channel=f1413c20e7ccaa&origin=https%3A%2F%2Fexample.com, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=false
[debug] [phantom] Successfully injected Casper client-side utilities
[info] [phantom] Step anonymous 12/28 https://example.com/category/section/ (HTTP 200)
WebPage Title: Section Name
[info] [phantom] Step anonymous 12/28: done in 81055ms.
[info] [phantom] Step _step 13/29 https://example.com/category/section/ (HTTP 200)
[info] [phantom] Step _step 13/29: done in 81075ms.
[info] [phantom] wait() finished waiting for 7000ms.
[info] [phantom] Step anonymous 14/30 https://example.com/category/section/ (HTTP 200)
****************
WebPage is loaded
****************
[object Object]
page.evaluate
- это как портал в другой мир, который не совпадает с нашим. Там может быть объект по имени obj
, но он не совпадает с obj
объявленным в начале вашего сценария CasperJs. Это разные объекты. Что происходит в page.evaluate
, остается на page.evaluate
- если вы специально не запросите возврат некоторых данных.
// This function will run inside of a web-page, not in the CasperJS script
function putInObject() {
var obj = {}; // UPDATED: here we also need to init this object
obj.title = document.querySelector('[itemprop="title"]').innerText;
obj.description = document.querySelector('[itemprop="description"]').innerText;
// return data from a web page context to CasperJS context
return obj;
}
...
// receive data in CasperJS context
obj = casper.evaluate(putInObject);
// If you want to view object contents
console.log(JSON.stringify(obj));
this.echo(obj);
получилnull
this.echo(obj);
, Вот исправленный код: pastebin.com/96D3dSVs . Оconsole.log(JSON.stringify(obj));
Я полагаю, следует использовать его в контексте веб-страницы, поэтому я помещаю его вputInObject()
перед операторомreturn
, но в моем терминале ничего не печаталось (журнал casperJS)obj
на веб-странице. Смотрите обновленный код и вот рабочий пример (хотя и в необработанном диалекте PhantomJS): pastebin.com/Yvhxe2cp