我创建了一个使用Scraper类刮取站点的CLI程序。我正在使用Nokogiri和Open-URI。上面的错误正在弹出。我在网上查看,没有找到帮助。
我确定该网站没有错字。
从CLI类中,我将站点用作arg创建一个新的Scraper类
class KefotoScraper::CLI
attr_accessor :kefoto_scraper
def initialize
site = "https://www.kefotos.mx"
@kefoto_scraper = Scraper.new(site)
end
end
在Scraper中,我有以下代码:
class Scraper
attr_accessor :doc, :product_names, :site, :name, :link
def initialize(site)
@site = site
@doc = doc
@product_names = product_names
@name = name
@link = link
@price_range = [].uniq
scrape_product
end
def get_html
@doc = Nokogiri::HTML(open(@site))
@product_names = doc.css(".navbar-nav li")
product_names
end
def scrape_product
get_html.each {|product|
@name = product.css("span").text
plink = product.css("a").attr("href").text
@link = "#{site}#{link}"
link_doc = Nokogiri::HTML(open(@link))
pr = link_doc.scan(/[\$£](\d{1,3}(,\d{3})*(\.\d*)?)/)
prices = pr_link.text
prices.each {|price|
if @price_range.include?(price[0]) == false
@price_range << price[0]
end
}
new_product = Products.new(@name, @price_range)
puts new_product
}
end
end
我收到以下错误:
scraper.rb:18:在'initialize'中:没有这样的文件或目录@ rb_sysopen-https://www.kefotos.mx(Errno :: ENOENT)
open
默认情况下对本地文件而不是URL起作用。您可以通过要求open-uri
库让它在URI上运行:
require 'open-uri'
这将使您的代码正常工作,但是使用适当的HTTP客户端读取HTTP文档是一种更好的做法,因为攻击者可能会使用超载的open()
来访问计算机硬盘上的文件。
例如,如果您仅使用net / http:
# At the top of your scraper.rb:
require 'net/http'
# Then, in your class:
link_doc = Nokogiri::HTML(Net::HTTP.get(URI(@link)))