2012-07-05 13 views
5

de análisis HTTPResponse con NokogiriRubí análisis HTTPResponse con Nokogiri

Hola, Tengo problemas para analizar objetos HttpResponse con Nokogiri.

puedo utilizar esta función para buscar un sitio web en:

buscar un enlace

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) 

cuando hago esto impresiones html un montón de galimatías y Nokogiri se queja de que "node_set debe ser un Nokogiri :: XML :: nodeset

Si alguien puede ofrecer ayuda sería muy apreciada

+1

usted debe utilizar en lugar de mecanizar este lío caliente. Se ocupa de los redireccionamientos y trata con las codificaciones para usted. – pguardiario

Respuesta

4

La primera cosa. SuEl métododevuelve un objeto Net::HTTPResponse y no solo el cuerpo. Debes proporcionar el cuerpo a Nokogiri.

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

He actualizado tu script por lo que es ejecutable (abajo). Un par de cosas no estaban definidas.

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 

El script no arroja errores e imprime el contenido. Es posible que esté obteniendo un error de Nokogiri debido al contenido que está recibiendo. Un problema común que he encontrado con Nokogiri es la codificación de caracteres. Sin el error exacto, es imposible saber qué está pasando.

Me recommnend mirando las siguientes preguntas StackOverflow

ruby 1.9: invalid byte sequence in UTF-8 (específicamente this answer)

How to convert a Net::HTTP response to a certain encoding in Ruby 1.9.1?

+0

Gracias, pero nokogiri todavía me da este error –

+0

Muchas gracias Sr.Simard, buscaré la codificación de caracteres. –

+0

¿Cómo puedo ver un mensaje de depuración más detallado? El único error que Nokogiri me está dando es que este node_set tiene que ser un Nokogiri :: XML :: Nodeset –