Casperjs/Phantomjs 修改 headers

问题描述 投票:0回答:2

我正在尝试更改一些标题,但没有任何效果:

var casper = require('casper').create({ // 
    stepTimeout: 15000, 
    verbose: false, 
    logLevel: 'error', 
    pageSettings: { 
        loadImages: true, 
        loadPlugins: true, 
        userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.364',
        customHeaders: { 
            Connection: 'keep-alive', 
            Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' 
} } });

我也尝试过:

phantom.page.customHeaders = { 
    "User-Agent" : "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0", 
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 
    "Accept-Language": "en-US,en;q=0.5", "Accept-Encoding": "gzip, deflate",
    "Connection" : "keep-alive" };

对于单个连接:

this.open('http://localhost/post.php', { 
    method: 'post', 
    headers: { 'Accept': 'application/json' } 
});

他们都不起作用还是我做错了什么? 谢谢

header phantomjs casperjs
2个回答
4
投票

我无法重现您的问题。这似乎对我有用...也许您在某个地方存在重定向问题,就像此处所讨论的那样。

我可以建议你像这个家伙一样尝试下面的代码吗?

casper.on('started', function () {
  this.page.customHeaders = {
    "User-Agent" : "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0", 
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", 
    "Accept-Language": "en-US,en;q=0.5",
    "Accept-Encoding": "gzip, deflate",
    "Connection" : "keep-alive"
  }
});

0
投票

也许有点晚了,但更优雅的解决方案是使用

.thenOpen
函数。

function thenOpen(location, settings, then)

虽然没有提供

.start
功能的位置 URL。一个例子如下:

var customHeaders = { "Cache-Control": "max-age=0" };
var casper = require('casper').create();
    
casper.start(  function() {
     });
    
casper.thenOpen( param_url , { headers: customHeaders }, function() {
      this.echo(this.getTitle());
    });
    
casper.run();
© www.soinside.com 2019 - 2024. All rights reserved.