在PhantomJS中获取页面的标题

Getting the title of the page in PhantomJS

本文关键字:标题 获取 PhantomJS      更新时间:2023-09-26

我正在尝试使用PhantomJS。这是一个简单的代码,它不像预期的那样工作。运行它后,我可以在控制台看到successfoo,但文档的标题是一个空字符串。

var page = require('webpage').create();
page.open('https://www.google.com', function(status) {
  console.log("Status: " + status);
  if(status === "success") {
    console.log("foo");
    console.log(document.title);
    phantom.exit();
  }
});

获取标题的简单方法是使用page.title

document.title没有给你任何东西的原因是因为PhantomJS有两个不同的上下文。只有页面上下文(在page.evaluate()内部)可以访问DOM,因此也可以访问document对象。外部上下文也有一个document对象,但它不做任何事情,因此只是一个虚拟对象。对于window也是如此。

另一种获取页面标题的方法是:

console.log(page.evaluate(function(){
    return document.title;
}));