I am trying to access a site with watir-webdriver. The site translates all the content to another language based on the "Accept-Language" request header, and the results are in the wrong language.

I'm trying to set the custom header, which phantomjs accepts (http://phantomjs.org/api/webpage/property/custom-headers.html), like so:

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

To test it out:

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

The Accept-Language header shown in resulting /tmp/headers.html does not match the one I specify. I have tried to write it as a json string but still no go.

有帮助吗?

解决方案

This worked for me:

$ 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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top