我正在制作吉他浏览CLI项目。我有不同吉他的名称和网址,如下所示:
def self.get_electric
doc = Nokogiri::HTML(open("https://reverb.com/c/electric-guitars"))
electrics = []
counter = 0
while counter < doc.css("h2:contains('Popular Electric Guitars')+div.overflowing-row__items ul.tiles.tiles--single-row.tiles--grow.tiles--three-wide li.tiles__tile").length
electric = {
name: doc.css("h2:contains('Popular Electric Guitars')+div.overflowing-row__items ul.tiles.tiles--single-row.tiles--grow.tiles--three-wide li.tiles__tile")[counter].text,
url: doc.css("h2:contains('Popular Electric Guitars')+div.overflowing-row__items ul.tiles.tiles--single-row.tiles--grow.tiles--three-wide li.tiles__tile a.marketing-callout__inner")[counter]["href"]
}
counter += 1
electrics << electric
end
electrics
HiStrung::Guitar.mass_create_electrics(electrics)
end
如果用户输入“ electric”或“ acoustic”,他们将获得吉他的名称和网址:
Enter here: electric
1. Fender Telecaster - https://reverb.com/marketplace/electric-guitars?query=telecaster
2. Gibson Les Paul - https://reverb.com/marketplace?query=les%20paul
3. Fender Stratocaster - https://reverb.com/marketplace/electric-guitars?query=stratocaster
4. Gibson SG - https://reverb.com/marketplace?query=sg
5. Fender Jazzmaster - https://reverb.com/marketplace?query=jazzmaster
现在,我希望我的程序做的是,当用户输入他们想了解的任何吉他的编号时,它将显示该吉他的价格和说明。价格和说明在另一个网址中。
我正在尝试一种方法来获取URL并获取价格和说明的html:
def self.get_electric_info(electric)
url = electric.url
doc = Nokogiri::HTML(url)
end
但我收到此名称错误:
pry(main)> HiStrung::Scraper.get_electric_info(electric)
NameError: undefined local variable or method `electric' for main:Object
from (pry):1:in `__pry__'
这是我的初始化类:
class HiStrung::Guitar
attr_accessor :name, :url
@@electrics = []
@@acoustics = []
def self.electrics
@@electrics
end
def self.acoustics
@@acoustics
end
def self.mass_create_electrics(electric_hash)
electric_hash.each do |e_hash|
electric = HiStrung::Guitar.new(e_hash[:name], e_hash[:url])
@@electrics << electric
end
end
def self.mass_create_acoustics(acoustic_hash)
acoustic_hash.each do |a_hash|
acoustic = HiStrung::Guitar.new(a_hash[:name], a_hash[:url])
@@acoustics << acoustic
end
end
def initialize(name, url)
@name, @url = name, url
end
结束
electric
变量。在调用方法之前,只需将electric
分配给您要获取其信息的Guitar对象。 类似这样的东西:
electric = HiStrung::Guitar.new("My name", "My url")
HiStrung::Scraper.get_electric_info(electric)
应该可以解决您的问题。干杯。