gpt4 book ai didi

Ruby 使用 Nokogiri 解析 HTTPresponse

转载 作者:数据小太阳 更新时间:2023-10-29 07:06:47 25 4
gpt4 key购买 nike

用 Nokogiri 解析 HTTPresponse

您好,我在使用 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

如果有人能提供帮助,我们将不胜感激

最佳答案

首先。您的 fetch 方法返回一个 Net::HTTPResponse 对象,而不仅仅是主体。你应该把尸体提供给 Nokogiri。

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 错误。我在使用 Nokogiri 时遇到的一个常见问题是字符编码。没有确切的错误,就不可能知道发生了什么。

我建议查看以下 StackOverflow 问题

ruby 1.9: invalid byte sequence in UTF-8 (特别是 this answer)

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

关于Ruby 使用 Nokogiri 解析 HTTPresponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11344802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com