我想检查某个网店上某个产品的价格。
我正在使用常量来存储网上商店数据的哈希值,因此编辑更容易(将添加更多商店)。
这是我正在使用的代码:
require 'httparty'
require 'nokogiri'
class Prijscheckr
STORES = {
:zara => {
'base_uri' => 'http://www.zara.com/nl/',
'normal_price_css' => 'p.price > span',
'css_normal_price_extract' => "[0].attr('data-price')",
'normal_price_xpath' => '/p[3]/span',
'xpath_normal_price_extract' => "[0].attr('data-price')"
}
}
def begin(args = {})
page = Nokogiri::HTML(HTTParty.get(args[:url]))
price = page.css(STORES[:zara]['normal_price_css'])STORES[:zara]['css_normal_price_extract']
end
end
做的时候
p = Prijscheckr.new
p.begin(url: 'http://www.zara.com/nl/nl/collectie-aw14/dames/jacks/leren-bikerjack-c269184p2137577.html')
结果如下:
# Works
# price = page.css('p.price > span')[0].attr('data-price')
# Works
# price = page.css(STORES[:zara]['normal_price_css'])[0].attr('data-price')
# Does not work
# price = page.css(STORES[:zara]['normal_price_css'])STORES[:zara]['css_normal_price_extract']
如何在没有在方法中对其进行硬编码的情况下连接price = page.css(STORES[:zara]['normal_price_css'])STORES[:zara]['css_normal_price_extract']
?
答案 0 :(得分:2)
不能通过连接字符串来创建Ruby代码。您可能希望将css_normal_price_extract
声明为lamba
'css_normal_price_extract' => ->(val) {val[0].attr('data-price')}
price = STORES[:zara]['css_normal_price_extract'].call(page.css(STORES[:zara]['normal_price_css']))