2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Mechanizeでgetする時にhttp://を省略してはまった件

Last updated at Posted at 2015-12-11

とあるサイトをスクレイピングしようとしてはまった。

単純にhttp://を省略するとエラーが発生する。

irb(main):004:0> require 'mechanize'
irb(main):005:0> agent = Mechanize.new
irb(main):006:0> p agent.get('google.co.jp')
ArgumentError: absolute URL needed (not google.co.jp)
        from /home/hogeuser/.rbenv/versions/2.2.0-rc1/lib/ruby/gems/2.2.0/gems/mechanize-2.7.3/lib/mechanize/http/agent.rb:651:in `resolve'
        from /home/hogeuser/.rbenv/versions/2.2.0-rc1/lib/ruby/gems/2.2.0/gems/mechanize-2.7.3/lib/mechanize/http/agent.rb:223:in `fetch'
        from /home/hogeuser/.rbenv/versions/2.2.0-rc1/lib/ruby/gems/2.2.0/gems/mechanize-2.7.3/lib/mechanize.rb:440:in `get'
        from (irb):6
        from /home/hogeuser/.rbenv/versions/2.2.0-rc1/bin/irb:11:in `<main>'

しかし、既に他のサイトをgetしていた場合、Mechanizeは相対パスを自動で補完しようとする。

irb(main):013:0> p agent.get('http://google.co.jp').uri
#<URI::HTTP http://www.google.co.jp/>
irb(main):014:0> p agent.get('google.co.jp').uri
Mechanize::ResponseCodeError: 404 => Net::HTTPNotFound for http://www.google.co.jp/google.co.jp -- unhandled response
        from /home/hogeuser/.rbenv/versions/2.2.0-rc1/lib/ruby/gems/2.2.0/gems/mechanize-2.7.3/lib/mechanize/http/agent.rb:308:in `fetch'
        from /home/hogeuser/.rbenv/versions/2.2.0-rc1/lib/ruby/gems/2.2.0/gems/mechanize-2.7.3/lib/mechanize.rb:440:in `get'
        from (irb):14
        from /home/hogeuser/.rbenv/versions/2.2.0-rc1/bin/irb:11:in `<main>'

この場合、
http://www.google.co.jp/google.co.jp
をgetしようとして404や403エラーになる。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?