6

Nokogiri で HTTPresponse を解析する

こんにちは、Nokogiri で HTTPresponse オブジェクトを解析できません。

この関数を使用して、ここで Web サイトを取得します。

リンクを取得する

def fetch(uri_str, limit = 10)
   
  
  # You should choose better exception.
  raise ArgumentError, 'HTTP redirect too deep' if limit == 0
  
  url = URI.parse(URI.encode(uri_str.strip))
  puts url
  
  #get path
  req = Net::HTTP::Get.new(url.path,headers)
  #start TCP/IP
  response = Net::HTTP.start(url.host,url.port) { |http|
        http.request(req)
  }
  case response
  when Net::HTTPSuccess
    then #print final redirect to a file
    puts "this is location" + uri_str
    puts "this is the host #{url.host}"
    puts "this is the path #{url.path}"
    
    return response
    # if you get a 302 response
  when Net::HTTPRedirection 
    then 
    puts "this is redirect" + response['location']
    return fetch(response['location'],aFile, limit - 1)
  else
    response.error!
  end
end




            html = fetch("http://www.somewebsite.com/hahaha/")
            puts html
            noko = Nokogiri::HTML(html)
            

私がこのhtmlを実行すると、意味不明なものがたくさん出力され、Nokogiriは「node_setはNokogiri::XML::NOdesetでなければならない」と不平を言います

誰かが助けを提供できれば、それは非常にありがたいです

4

1 に答える 1

5

初めにすること。メソッドは、本体だけでなくオブジェクトをfetch返します。Net::HTTPResponseノコギリに体を提供する必要があります。

response = fetch("http://www.somewebsite.com/hahaha/")
puts response.body
noko = Nokogiri::HTML(response.body)

実行できるようにスクリプトを更新しました(以下)。いくつかのことが未定義でした。

require 'nokogiri'
require 'net/http'

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

  url = URI.parse(URI.encode(uri_str.strip))
  puts url

  #get path
  headers = {}
  req = Net::HTTP::Get.new(url.path,headers)
  #start TCP/IP
  response = Net::HTTP.start(url.host,url.port) { |http|
        http.request(req)
  }

  case response
  when Net::HTTPSuccess
    then #print final redirect to a file
    puts "this is location" + uri_str
    puts "this is the host #{url.host}"
    puts "this is the path #{url.path}"

    return response
    # if you get a 302 response
  when Net::HTTPRedirection
    then
    puts "this is redirect" + response['location']
    return fetch(response['location'], limit-1)
  else
    response.error!
  end
end

response = fetch("http://www.google.com/")
puts response
noko = Nokogiri::HTML(response.body)
puts noko

スクリプトはエラーを出さず、コンテンツを出力します。受信しているコンテンツによっては、のこぎりエラーが発生する場合があります。Nokogiri でよく遭遇する問題の 1 つは、文字エンコードです。正確なエラーがなければ、何が起こっているのかわかりません。

次のStackOverflowの質問を見ることをお勧めします

ruby 1.9: UTF-8 の無効なバイト シーケンス (具体的にはこの回答)

Ruby 1.9.1でNet::HTTPレスポンスを特定のエンコーディングに変換するには?

于 2012-07-05T13:02:25.547 に答える