PhantomJS querySelectorAll().textcontent returns 没有

PhantomJS querySelectorAll().textcontent returns nothing

我使用 phantomjs 创建了一个简单的网络抓取工具来从网站抓取数据。当我使用 querySelectorAll 获取我想要的内容时,它对我不起作用。这是我的全部代码。

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

var url = 'https://www.google.com.kh/?gws_rd=cr,ssl&ei=iE7jV87UKsrF0gSDw4zAAg';

page.open(url, function(status){

  if(status === 'success'){

    var title = page.evaluate(function(){
      return document.querySelectorAll('.logo-subtext')[0].textContent;
    });

    console.log(title);
  }
  phantom.exit();
});

请帮我解决这个问题。

非常感谢。

默认情况下,PhantomJS 的虚拟屏幕大小为 400x300。

var page = require('webpage').create();
console.log(page.viewportSize.width);
console.log(page.viewportSize.height);

400
300

有些网站注意到了这一点,他们提供了 HTML 和 CSS 的移动精简版,而不是您在桌面浏览器中看到的普通版本。但是我们可以通过设置所需的视口大小来解决这个问题:

page.viewportSize = { width: 1280, height: 800 };

还有一些网站会进行用户代理嗅探并据此做出决定。如果他们不知道你的浏览器,他们可以显示一个移动版本以确保安全,或者如果他们不想被抓取,他们可以拒绝连接到 PhantomJS,因为它诚实地声明自己:

console.log(page.settings.userAgent);

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1

但我们可以设置所需的用户代理:

 page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0';

当处理如此脆弱的东西和网络抓取时,您真的应该注意您可能收到的任何错误和系统消息。

所以 PhantomJS 脚本不应该没有 onError 和 onConsoleMessage 回调:

page.onError = function (msg, trace) {
    var msgStack = ['ERROR: ' + msg];
    if (trace && trace.length) {
      msgStack.push('TRACE:');
      trace.forEach(function(t) {
        msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function +'")' : ''));
      });
    }
    console.log(msgStack.join('\n'));
};   

page.onConsoleMessage = function (msg) {
    console.log(msg);
};   

PhantomJS 脚本调试的另一个重要技术是截图。 你确定 PhantomJS 能看到你所看到的吗 Chrome?

 page.render("google.com.png");

设置用户代理之前:

设置 Firefox 用户代理后