HOWTO set a user agent for Ruby Mechanize

This guide will show you how to set a custom user agent header for Ruby Mechanize, or use one of the built-in browser aliases.


Setting a custom user agent

Use the Mechanize#user_agent= method to set a custom user agent. For example:

require 'mechanize'

mechanize = Mechanize.new

mechanize.user_agent = 'ACME-Examplebot/1.0'

By convention the user agent header should include a list of "product tokens" (product name and version), listed in order of significance.

Setting a custom user agent in Rails

Inside a Rails application you can set the user agent to the application name like this:

mechanize.user_agent = Rails.application.class.parent_name

Using a built-in user agent alias

To emulate a browser, use the Mechanize#user_agent_alias= method to specify one of the built-in user agent aliases. For example:

mechanize.user_agent_alias = 'Mac Safari'

You could also use the Array#sample method to select a random alias like this:

aliases = ['Linux Firefox', 'Windows Chrome', 'Mac Safari']

mechanize.user_agent_alias = aliases.sample

Looking for more information about Ruby Mechanize? Read the HOWTO scrape websites with Ruby & Mechanize guide, or grab yourself a copy of the Ruby Mechanize Handbook.

Need a quick reference for commonly used Mechanize methods? Sign-up below!

Get your free Mechanize & Nokogiri cheat sheet

PLUS: actionable tips on how to improve your Ruby code and advice on how to increase your value as a Ruby developer, delivered straight to your inbox. No spam, ever.

Unsubscribe at any time.