如何使用自定义window.navigator对象创建phantomJS实例?

时间:2014-05-08 17:33:30

标签: javascript phantomjs headless-browser

如何在创建过程中将自定义window.navigator对象应用于PhantomJS的WebPage对象?当我尝试自定义导航器时,我仍然在console.log('The default user agent is ' + page.settings.userAgent);

时收到默认值

到目前为止我所拥有的:

console.log('hello');
var page = require('webpage').create();
page.onInitialized = function() {
  page.evaluate(function() {
    var newNavigator = Object.create(window.navigator);
    newNavigator.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36';
    window.navigator = newNavigator;
  });
};
page.open('http://www.google.com', function(status) {
  if (status !== 'success') {
    console.log('Unable to access network');
  } else {
console.log('The default user agent is ' + page.settings.userAgent);
}});

运行上述js时控制台的内容:

hello
The default user agent is Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.34
(KHTML, like Gecko) PhantomJS/1.9.7 Safari/534.34
^C

1 个答案:

答案 0 :(得分:2)

您不需要也不能使用evaluate来设置导航器。您可以通过设置进行设置。所以以下内容适用于phantomjs 1.9.7:

page.onInitialized = function() {
    page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36';
};

<强>输出

hello
The default user agent is Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36
^C