43

URLを取得し、HTTPGETを使用してクエリをページに渡します。(の)最新のフレーバーで何が起こるかとnet/httpいうと、スクリプトは302応答を超えないということです。私はいくつかの異なる解決策を試しました。HTTPClient、net / http、Rest-Client、Patron ..

そのページのhtmlの属性タグを検証するために、最後のページに進む方法が必要です。リダイレクトは、モバイルユーザーエージェントがモバイルビューにリダイレクトするページにヒットするため、ヘッダーにモバイルユーザーエージェントが含まれるためです。これが今日の私のコードです:

require 'uri'
require 'net/http'

class Check_Get_Page

    def more_http
        url = URI.parse('my_url')
        req, data = Net::HTTP::Get.new(url.path, {
        'User-Agent' => 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5'
        })
        res = Net::HTTP.start(url.host, url.port) {|http|
        http.request(req)
            }
        cookie = res.response['set-cookie']
        puts 'Body = ' + res.body
        puts 'Message = ' + res.message
        puts 'Code = ' + res.code
        puts "Cookie \n" + cookie
    end

end

m = Check_Get_Page.new
m.more_http

任意の提案をいただければ幸いです!

4

6 に答える 6

73

リダイレクトを追跡するには、次のようなことを行うことができます(ruby-docから取得

リダイレクト後

require 'net/http'
require 'uri'

def fetch(uri_str, limit = 10)
  # You should choose better exception.
  raise ArgumentError, 'HTTP redirect too deep' if limit == 0

  url = URI.parse(uri_str)
  req = Net::HTTP::Get.new(url.path, { 'User-Agent' => 'Mozilla/5.0 (etc...)' })
  response = Net::HTTP.start(url.host, url.port, use_ssl: true) { |http| http.request(req) }
  case response
  when Net::HTTPSuccess     then response
  when Net::HTTPRedirection then fetch(response['location'], limit - 1)
  else
    response.error!
  end
end

print fetch('http://www.ruby-lang.org/')
于 2011-08-03T23:23:51.677 に答える
8

リダイレクトするURLを指定します

url = 'http://httpbin.org/redirect-to?url=http%3A%2F%2Fhttpbin.org%2Fredirect-to%3Furl%3Dhttp%3A%2F%2Fexample.org'

A。Net::HTTP

begin
  response = Net::HTTP.get_response(URI.parse(url))
  url = response['location']
end while response.is_a?(Net::HTTPRedirection)

リダイレクトが多すぎる場合は、必ずケースを処理してください。

B。OpenURI

open(url).read

OpenURI::OpenRead#openデフォルトではリダイレクトに従いますが、リダイレクトの数を制限するものではありません。

于 2018-06-27T22:57:49.460 に答える
5

ここに示した例に基づいて、このための別のクラスを作成しました。皆さん、どうもありがとうございました。Cookie、パラメーター、および例外を追加し、最終的に必要なものを取得しました:https ://gist.github.com/sekrett/7dd4177d6c87cf8265cd

require 'uri'
require 'net/http'
require 'openssl'

class UrlResolver
  def self.resolve(uri_str, agent = 'curl/7.43.0', max_attempts = 10, timeout = 10)
    attempts = 0
    cookie = nil

    until attempts >= max_attempts
      attempts += 1

      url = URI.parse(uri_str)
      http = Net::HTTP.new(url.host, url.port)
      http.open_timeout = timeout
      http.read_timeout = timeout
      path = url.path
      path = '/' if path == ''
      path += '?' + url.query unless url.query.nil?

      params = { 'User-Agent' => agent, 'Accept' => '*/*' }
      params['Cookie'] = cookie unless cookie.nil?
      request = Net::HTTP::Get.new(path, params)

      if url.instance_of?(URI::HTTPS)
        http.use_ssl = true
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end
      response = http.request(request)

      case response
        when Net::HTTPSuccess then
          break
        when Net::HTTPRedirection then
          location = response['Location']
          cookie = response['Set-Cookie']
          new_uri = URI.parse(location)
          uri_str = if new_uri.relative?
                      url + location
                    else
                      new_uri.to_s
                    end
        else
          raise 'Unexpected response: ' + response.inspect
      end

    end
    raise 'Too many http redirects' if attempts == max_attempts

    uri_str
    # response.body
  end
end

puts UrlResolver.resolve('http://www.ruby-lang.org')
于 2016-01-22T08:32:48.443 に答える
3

私のために働いたリファレンスはここにあります:http ://shadow-file.blogspot.co.uk/2009/03/handling-http-redirection-in-ruby.html

ほとんどの例(ここで受け入れられた回答を含む)と比較すると、ドメイン(http://example.com-/を追加する必要があります)であるURLを処理し、SSLを具体的に処理し、相対URLも処理するため、より堅牢です。

もちろん、ほとんどの場合、RESTClientのようなライブラリを使用する方がよいでしょうが、低レベルの詳細が必要な場合もあります。

于 2014-04-18T13:14:28.540 に答える
1

たぶん、ここでcurb-fu gemを使用できますhttps://github.com/gdi/curb-fu唯一のことは、リダイレクトに従うようにするための追加のコードです。私は以前に以下を使用しました。それが役に立てば幸い。

require 'rubygems'
require 'curb-fu'

module CurbFu
  class Request
    module Base
      def new_meth(url_params, query_params = {})
        curb = old_meth url_params, query_params
        curb.follow_location = true
        curb
      end

      alias :old_meth :build
      alias :build :new_meth
    end
  end
end

#this should follow the redirect because we instruct
#Curb.follow_location = true
print CurbFu.get('http://<your path>/').body
于 2011-08-04T02:24:26.080 に答える
0

各リダイレクトの詳細を気にする必要がない場合は、ライブラリMechanizeを使用できます。

require 'mechanize'

agent = Mechanize.new
begin
    response = @agent.get(url)
rescue Mechanize::ResponseCodeError
    // response codes other than 200, 301, or 302
rescue Timeout::Error
rescue Mechanize::RedirectLimitReachedError
rescue StandardError
end

宛先ページを返します。または、これによってリダイレクトをオフにすることができます:

agent.redirect_ok = false

または、オプションでリクエストに応じていくつかの設定を変更できます

agent.user_agent = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Mobile Safari/537.36"
于 2020-02-26T02:17:21.537 に答える