【发布时间】:2012-07-05 21:14:58
【问题描述】:
使用 Nokogiri 解析 HTTP 响应
您好,我在使用 Nokogiri 解析 HTTPresponse 对象时遇到问题。
我在这里使用这个函数来获取一个网站:
获取链接
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
如果有人能提供帮助将不胜感激
【问题讨论】:
-
你应该使用机械化而不是这个热的烂摊子。它负责重定向并为您处理编码。