0

To test out using JavaScript with PhantomJS I'm trying to write a script that will go to the url "http://phantomjs.org/quick-start.html" and then click on the PhantomJS logo bringing the page to the PhantomJS homepage. My goal is to navigate to a url and successfully click on an html element. However I am getting the error:

TypeError: 'null' is not an object (evaluating 'document.querySelector('img [alt
="PhantomJS"]').click')

  phantomjs://webpage.evaluate():3

  phantomjs://webpage.evaluate():5

  phantomjs://webpage.evaluate():5

Here is my code:

var page = require('webpage').create();

page.open('http://phantomjs.org/quick-start.html', function(status) {
console.log(status);
page.render('websiteBeforeClick.png');

page.evaluate(function() {
  document.querySelector('img [alt="PhantomJS"]').click();
});    

page.render('websiteAfterClick.png');
phantom.exit();
});

Is my css selector incorrect?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
user3803788
  • 37
  • 1
  • 2
  • 6

1 Answers1

0

If you go on that page and run document.querySelector('img [alt ="PhantomJS"]') you'll see that it already returns null there.

It's because of the space before the [ in your selector. Try document.querySelector('img[alt="PhantomJS"]').

That is your first problem. Then you're trying to use click but that won't work, you need to dispatch a click event. See this other Stack Overflow question for a solution to that problem.

Community
  • 1
  • 1
dee-see
  • 23,668
  • 5
  • 58
  • 91