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

查看:87
本文介绍了如何在幻影模块中设置用户代理字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

when I use phantomjs I try and set the header for userAgent using three different ways but when I visit the page and save the PHP $_SERVER object to a txt pad I still see 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

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

not only that but the output of the page is also undefined.

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

It seems that the docs have changed or I cant find the correct ones. I am looking at

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

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

如何正确使用?

推荐答案

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

According to the Functional Details in the docs, you have to set the user agent through 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来实现.

It has to be done this way, because the bridge has to communicate with the PhantomJS process and isn't doing this in a non-asynchronous fashion. This could've probably been implemented with Object.defineProperty.

如果您想一次设置多个设置,可以执行( ref ):

If you want to set multiple settings at once, you can do (ref):

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 .

You can find a list of settings that you can set in page.settings.

这篇关于如何在幻影模块中设置用户代理字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆