Mechanizeでformをsubmitしたときに' can't convert nil into String (TypeError)'と言われた場合の対応
自分の場合 Googleアカウントの認証を Mechanizeで通そうとしたときのこのエラーに遭遇した。
/opt/local/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/util.rb:40:in `iconv': can't convert nil into String (TypeError) from /opt/local/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/util.rb:40:in `from_native_charset' from /opt/local/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:152:in `from_native_charset' from /opt/local/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:144:in `proc_query' from /opt/local/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:143:in `map' from /opt/local/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:143:in `proc_query' from /opt/local/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:166:in `build_query' from /opt/local/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:165:in `each' from /opt/local/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:165:in `build_query' from /opt/local/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize/form.rb:214:in `request_data' from /opt/local/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize.rb:401:in `post_form' from /opt/local/lib/ruby/gems/1.8/gems/mechanize-0.9.3/lib/www/mechanize.rb:344:in `submit' from get_apikey.rb:15:in `get_apikey' from get_apikey.rb:23
Mechanizeのバージョンは 0.9.3
エラーが出ている箇所のコードは
login_form = page.forms[0] ... agent.submit(login_form)
でsubmitしているところで発生していた。
よくよく調べるとPage
オブジェクトのencoding
の値がnil
になっているために例外が発生しているようだったので、強引に、
page.parser.encoding = 'utf-8'
とかやってあげたら、とりあえずエラーになんなくなった。
Mechanizeのバグ?なのかなー?
あとで、バグ報告あげておこう...