在watir-webdriver和phantomjs中设置“Accept-Language”标题

时间:2013-12-13 09:51:50

标签: ruby selenium selenium-webdriver phantomjs watir-webdriver

我正在尝试使用watir-webdriver访问网站。该网站根据“Accept-Language”请求标题将所有内容翻译为另一种语言,结果使用错误的语言。

我正在尝试设置自定义标头,phantomjs接受(http://phantomjs.org/api/webpage/property/custom-headers.html),如下所示:

require 'watir-webdriver'
capabilities = Selenium::WebDriver::Remote::Capabilities.phantomjs(
"phantomjs.page.settings.userAgent" => "Mozilla/5.0",
"phantomjs.page.customHeaders" => {'Accept-Language' => 'en-GB,en-US;q=0.8,en;q=0.6' }
)
b = Watir::Browser.new :phantomjs, :desired_capabilities => capabilities

测试一下:

b.goto 'http://pgl.yoyo.org/http/browser-headers.php'
File.open("/tmp/headers.html", "w") { |io|
  io.write b.html
}

结果Accept-Language中显示的/tmp/headers.html标头与我指定的标头不匹配。我试图把它写成一个json字符串,但仍然没有。

1 个答案:

答案 0 :(得分:5)

这对我有用:

$ phantomjs -v
1.9.2

$ gem search -l webdriver
*** LOCAL GEMS ***
selenium-webdriver (2.38.0)
watir-webdriver (0.6.4)

$ irb 

irb(main):001:0> require "watir-webdriver"
=> true

irb(main):002:0> capabilities = Selenium::WebDriver::Remote::Capabilities.phantomjs
=> #<Selenium::WebDriver::Remote::Capabilities:0x007fbbeb8faa08 @capabilities={:browser_name=>"phantomjs", :version=>"", :platform=>:any, :javascript_enabled=>true, :css_selectors_enabled=>true, :takes_screenshot=>true, :native_events=>false, :rotatable=>false, :firefox_profile=>nil, :proxy=>nil}>

irb(main):003:0> capabilities['phantomjs.page.customHeaders.Accept-Language'] = 'ru-RU'
=> "ru-RU"

irb(main):004:0> browser = Watir::Browser.new :phantomjs, desired_capabilities: capabilities
=> #<Watir::Browser:0x5be4c6adc1d41736 url="about:blank" title="">

irb(main):005:0> browser.goto "httpbin.org/headers"
=> "http://httpbin.org/headers"

irb(main):006:0> puts browser.html
<html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">{
  "headers": {
    "Accept-Encoding": "gzip",
    "User-Agent": "Mozilla/5.0 (Macintosh; PPC Mac OS X) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.2 Safari/534.34",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Connection": "close",
    "Accept-Language": "ru-RU",
    "Host": "httpbin.org"
  }
}</pre></body></html>
=> nil