I've a task to test different user agents on a URL through automation. I'm using ruby to code, and I've been trying to set an user agent using the following method, but it doesn't seem to recognize the user agent.
@http = Net::HTTP.new(URL)
response = @http.request_get(URL, {'User-Agent' => useragent})
Is there any other way to do this, or what am I doing wrong?
http = Net::HTTP.new("your.site.com", 80)
req = Net::HTTP::Get.new("/path/to/the/page.html", {'User-Agent' => 'your_agent'})
response = http.request(req)
puts response.body
Works great for me.
Also another that work for me :
require 'open-uri'
html = open('http://your.site.com/the/page.html', 'User-Agent' => 'Ruby').read
puts html
Hope this will help you.
The included Net::HTTPHeader has the initialize_http_header method:
@http = Net::HTTP.new(URL)
@http.initialize_http_header({'User-Agent' => useragent})
response = @http.request_get(URL)
HTH
来源:https://stackoverflow.com/questions/5798037/how-to-set-a-custom-user-agent-in-ruby