如何在phantom模块中设置用户代理字符串?[英] How to set the user agent string in the phantom module?

问题描述

var phantom = require('phantom');
console.dir(phantom);
phantom.create(function(browser){
    browser.createPage(function(page){
        page.customHeaders={
            "HTTP_USER_AGENT": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36",
            };
        console.dir(page.settings);
        //undefined
        page.settings={};
        page.settings.userAgent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36';
        page.settings.HTTP_USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36';
        console.dir(page.settings);
        page.open('http://example.com/req.php', function() {
            setTimeout(function() {
                var output = page.evaluate(function() {
                    return document;
                    });
                console.dir(output);
                //undefined
                }, 1000);
             });});});

当我使用 phantomjs 时,我尝试使用三种不同的方式为 userAgent 设置标题,但是当我访问页面并将 PHP $_SERVER 对象保存到 txt pad 时,我仍然看到 PhantomJS

HTTP_USER_AGENT: Mozilla/5.0 (Unknown; Linux x86_64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.0.1-development Safari/538.1

不仅如此,页面的输出也是未定义的.

似乎文档已更改,或者我找不到正确的文档.我在看

http://phantomjs.org/api/webpage/property/settings.html

https://www.npmjs.com/package/phantom

如何正确使用?

解决方案

根据Functional文档中的详细信息,您必须通过page.set()设置用户代理:

page.set('settings.userAgent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36');

必须以这种方式完成,因为桥必须与 PhantomJS 进程进行通信,而不是以非异步方式进行.这可能已经用 Object.defineProperty 实现了.

如果你想一次设置多个设置,你可以这样做 (参考):

page.set('settings', {
    userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11",
    javascriptEnabled: false,
    loadImages: false
});

您可以在 page.settings.

本文地址:https://www.itbaoku.cn/post/1740041.html