Tuesday, December 15, 2009

Mechanize TypeError: can't convert nil into String

Problem

>> page = agent.submit(login_form)
TypeError: can't convert nil into String
        from /usr/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/util.rb:40:in `iconv'
        from /usr/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/util.rb:40:in `from_native_charset'
        from /usr/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:152:in `from_native_charset'
        from /usr/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:144:in `proc_query'
        from /usr/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:143:in `map'
        from /usr/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:143:in `proc_query'
        from /usr/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:166:in `build_query'
        from /usr/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:165:in `each'
        from /usr/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:165:in `build_query'
        from /usr/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:214:in `request_data'
        from /usr/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize.rb:401:in `post_form'
        from /usr/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize.rb:344:in `submit'

Patch(Line 40)

root@khojguru:~# vi /usr/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/util.rb
...
def from_native_charset(s, code)
  if Mechanize.html_parser == Nokogiri::HTML
    return unless s
    - Iconv.iconv(code, "UTF-8", s).join("")
    + Iconv.iconv(code.to_s, "UTF-8", s.to_s).join("")
  else
    return s
  end
end
...

2 comments:

  1. Thats the most bizarre error, but I'm so glad you posted your fix! I have two identical machines, both with the same version of Mechanize, and for some reason one of the machines was breaking with this exact error. Thank you for posting your patch, it saved me hours!

    ReplyDelete