PhantomJS - customHeaders 属性
customHeaders 函数指定页面发出的每个请求将发送到服务器的附加 HTTP 请求标头。默认值为空对象"{}"。标头名称和值在发送到服务器之前以 US-ASCII 编码。
语法
其语法如下 −
var wpage = require('webpage').create();
wpage.customHeaders = {
//指定标头
};
示例
以下示例显示了 customHeaders 属性的用法。
var page = require('webpage').create();
var server = require('webserver').create();
var port = 8080;
var listening = server.listen(8080, function (request, response) {
console.log("GOT HTTP REQUEST");
console.log(JSON.stringify(request, null, 4));
});
var url = "http://localhost:" + port + "/foo/response.php";
console.log("sending request to :" +url);
page.customHeaders = {'Accept-Language' : 'en-GB,en-US;q = 0.8,en;q = 0.6'};
//此处提到了其他标题
page.open(url, function (status) {
if (status !== 'success') {
console.log('page not opening');
} else {
console.log("Getting response from the server:");
}
phantom.exit();
});
Output with customheader
上述程序生成以下输出。
sending request to :http://localhost:8080/foo/response.php
GOT HTTP REQUEST {
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q = 0.9,*/*;q = 0.8",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-GB,en-US;q = 0.8,en;q = 0.6",
"Connection": "Keep-Alive",
"Host": "localhost:8080",
"User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1"
},
"httpVersion": "1.1",
"method": "GET",
"url": "/foo/response.php"
}
在上面的例子中,我们使用 customheader 来设置 Accept-Language,同样的内容也显示在 http 标头中。
没有 customheader 的输出
上面的程序在没有 customheader 的情况下生成以下输出。
sending request to :http://localhost:8080/foo/response.php
GOT HTTP REQUEST {
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q = 0.9,*/*;q = 0.8",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-IN,*",
"Connection": "Keep-Alive",
"Host": "localhost:8080",
"User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1"
},
"httpVersion": "1.1",
"method": "GET",
"url": "/foo/response.php"
}
如果没有自定义标头,则接受语言如上输出所示。使用 customheader 属性,您可以更改所需的 http 标头。
phantomjs_webpage_module_properties.html

