selenium 怎样设置请求头
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了selenium 怎样设置请求头相关的知识,希望对你有一定的参考价值。
参考技术A lib/request_headers.rb:class CustomHeadersHelper
cattr_accessor :headers
end
class RequestHeaders
def initialize(app, helper = nil)
@app, @helper = app, helper
end
def call(env)
if @helper
headers = @helper.headers
if headers.is_a?(Hash)
headers.each do |k,v|
env["HTTP_#k.upcase.gsub("-", "_")"] = v
end
end
end
@app.call(env)
end
end
config/initializers/middleware.rb
require 'request_headers'
if %w(test cucumber).include?(Rails.env)
Rails.application.config.middleware.insert_before Rack::Lock, "RequestHeaders", CustomHeadersHelper
end
spec/support/capybara_headers.rb
require 'request_headers'
module CapybaraHeaderHelpers
shared_context "navigating within the site" do
before(:each) add_headers("Referer" => Capybara.app_host + "/")
end
def add_headers(custom_headers)
if Capybara.current_driver == :rack_test
custom_headers.each do |name, value|
page.driver.browser.header(name, value)
end
else
CustomHeadersHelper.headers = custom_headers
end
end
end
spec/spec_helper.rb
...
config.include CapybaraHeaderHelpers
selenium设定请求头
如果只是需要设定User-Agent可以用如下所示方式
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.103 Safari/537.36" )
browser = webdriver.PhantomJS(desired_capabilities=dcap)
如果是全请求头设定的话(此处是转载自他人博客内容转载地址如下:http://www.cnblogs.com/zhao-ying-jie/p/7082723.html)
headers = { \'Accept\': \'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\', \'Accept-Language\': \'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3\', \'User-Agent\': \'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4\', \'Connection\': \'keep-alive\' }
cap = DesiredCapabilities.PHANTOMJS.copy()//使用copy()防止修改原代码定义dict
for key, value in headers.items(): cap[\'phantomjs.page.customHeaders.{}\'.format( key)] = value
browser = webdriver.PhantomJS(desired_capabilities=cap)
以上是关于selenium 怎样设置请求头的主要内容,如果未能解决你的问题,请参考以下文章