I'm having difficulty setting the user-agent
. As you can see my custom user_agent_alias
is not being returned. Can someone please explain why this isn't working and how I can fix this?
require 'rubygems'
require 'mechanize'
require 'nokogiri'
m = Mechanize.new
m.user_agent_alias = 'My Custom User Agent'
page = m.get("http://whatsmyuseragent.com/")
html = Nokogiri::HTML(page.body)
puts html.xpath('//*[(@id = "body_lbUserAgent")]').map(&:content)
Below is the "user agent" being returned (not what I set):
Mechanize/2.7.3 Ruby/2.0.0p353 (http://github.com/sparklemotion/mechanize/)
Turns out that the issue was that user_agent_alias
requires a specific type. All acceptable types are as follows:
Working code:
require 'rubygems'
require 'mechanize'
m = Mechanize.new
m.user_agent_alias = 'Mac Safari 4'
page = m.get("http://whatsmyuseragent.com/")
html = Nokogiri::HTML(page.body)
puts html.xpath('//*[(@id = "body_lbUserAgent")]').map(&:content)
It is actually possible to set any user agent string: you have to use the method Mechanize::Agent#user_agent=
instead of Mechanize::Agent#user_agent_alias=
.
So if you change your example to:
m = Mechanize.new
m.user_agent = 'My Custom User Agent'
page = m.get("http://whatsmyuseragent.com/")
Then it works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With