1

I want the following Casperjs script to open Google, search a term, and log the title of the page:

var title = ""
var casper = require('casper').create({
  verbose: true,
  logLevel: 'debug',
  pageSettings: {
    loadImages: false, // The WebPage instance used by Casper will
    loadPlugins: false // use these settings
    //userAgent: 'Mozilla/5.0 (Macintosh Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4'
  }
})

casper.start('http://google.co.uk/', function() {
  // search for 'casperjs' from google form
  this.fill('form[action="/search"]', {
    q: 'casperjs'
  }, true)
})

casper.thenEvaluate(function() {
  // aggregate results for the 'casperjs' search
  title = document.title
})

casper.log(title, 'warning')

casper.run()

But outputs nothing:

[warning] [phantom]

What am I doing wrong?

alexchenco
  • 53,565
  • 76
  • 241
  • 413

1 Answers1

2

There are two problems with your code.

This should work:

casper.then(function() {
    var title = this.evaluate(function() {
      return document.title
    })

    this.log(title, 'warning')
})

or even this:

casper.then(function() {
    var title = this.getTitle()

    this.log(title, 'warning')
})
Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • Thanks, I'm just learning CasperJS. So the problem was, I was executing the `log` asynchronously (e.g. before `title` had any value? And using `casper.log` instead of `this.log`? – alexchenco Dec 22 '15 at 17:01
  • Oh, `casper.log` also works in your example. What's the difference, then, between using `casper.log` and `this.log`? – alexchenco Dec 22 '15 at 17:03
  • 1
    There is no difference between `casper.log` and `this.log` if `this.log` is called inside of a CasperJS step function or event handler. – Artjom B. Dec 22 '15 at 17:04