1
0

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.

401 => Net::HTTPUnauthorized for https スクレイピングで認証拒否された時

Posted at

スクレイピングで見たことがないエラーが出て、調べてみたら日本語の記事が多くなかったので書いておきます。

エラー:japanese_ogre:

concole

$ ruby scraping.rb

エラー文

response_authenticate': 401 => Net::HTTPUnauthorized for https: URL名 -- no credentials found, provide some with #add_auth -- available realms: Application (Mechanize::UnauthorizedError)

原因:smiling_imp:

認証エラーっぽいです。。

Basic認証が使用されている場合、ユーザ名とパスワードの組み繋ぎ、
Base64で暗号化されて、サーバーに送信されるようです。

認証が必要なページにアクセスしようとした場合に、サーバ側は「Authorization」と言うヘッダーが
ブラウザからのリクエストに付いているかどうかを確認します。
最初にアクセスした時には「Authorization」ヘッダーがありませんのでブラウザに対して認証が必要になるみたいです

なので、上記の問題が発生した場合に対処できるのは、Authorizationヘッダーを自分で渡せばいいようです!

要はアクセスするためには認証用の暗号が必要ですよ!って言われているようです。
(間違っていればご指摘ください)

解決:hugging:

require 'mechanize'

username = 'ユーザー名'
password = 'パスワード' #この辺は管理者に聞くしかないかと思われます、、

agent = Mechanize.new do |agent|
  agent.pre_connect_hooks << lambda { |agent, request| request["Authorization"] = "Basic #{Base64.strict_encode64(username + ':' + password)}" }
end

page = agent.get("URL")
  elements = page.search('a div') # a要素の下のdiv要素を検索
    elements.each do |ele|
    puts ele.inner_text # inner_textメソッドでテキストを取得
end

これでスクレイピング可能かと思います:thinking:

参考

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?