2

我正在尝试废弃锚链接之间的 52:

<div class="zg_usedPrice">
<a href="http://www.amazon.com/gp/offer-listing/B000O3GCFU/ref=zg_bs_baby-products_price?ie=UTF8&condition=new">52&nbsp;new</a>
</div>

使用此代码:

 def self.parse_products
    product_hash = {}
    product = @data.css('#zg_centerListWrapper')

    product.css('.zg_itemImmersion').each do | product |
      product_name = product.css('.zg_title a').text
      product_used_price_status = product.css('.zg_usedPrice > a').text[/(\D+)/]
      product_hash[:product] ||= []
      product_hash[:product] << { :name             => product_name,
                                  :used_status      => product_used_price_status }
    end 

    product_hash
  end

但我认为http://www.amazon.com/gp/offer-listing/B000O3GCFU/ref=zg_bs_baby-products_price?ie=UTF8&condition=newURL 中的部分会产生以下错误:

Encoding::UndefinedConversionError:
   U+00A0 from UTF-8 to US-ASCII
 # ./parser_spec.rb:175:in `block (2 levels) in <top (required)>'

我尝试了他们在“ Ruby error UTF-8 to ASCII ”中的建议,但我仍然遇到同样的问题。有什么解决方法吗?


完整的错误跟踪:

  1) Product (Baby) should return correct keys
     Failure/Error: expect(product_hash[:product]["Pet Supplies"].keys).to eq(["Birds", "Cats", "Dogs", "Fish & Aquatic Pets", "Horses", "Insects", "Reptiles & Amphibians", "Small Animals"])
     TypeError:
       can't convert String into Integer
     # ./parser_spec.rb:179:in `[]'
     # ./parser_spec.rb:179:in `block (2 levels) in <top (required)>'

  2) Product (Baby) should return correct values
     Failure/Error: expect(product_hash[:product]["Pet Supplies"].values).to eq([16281, 245512, 513926, 46811, 14805, 364, 5816, 19769])
     TypeError:
       can't convert String into Integer
     # ./parser_spec.rb:183:in `[]'
     # ./parser_spec.rb:183:in `block (2 levels) in <top (required)>'

  3) Product (Baby) should return correct hash
     Failure/Error: expect(product_hash[:product]).to eq({"Pet Supplies"=>{"Birds"=>16281, "Cats"=>245512, "Dogs"=>513926, "Fish & Aquatic Pets"=>46811, "Horses"=>14805, "Insects"=>364, "Reptiles & Amphibians"=>5816, "Small Animals"=>19769}})
     Encoding::UndefinedConversionError:
       U+00A0 from UTF-8 to US-ASCII
     # ./parser_spec.rb:187:in `block (2 levels) in <top (required)>'
4

1 回答 1

1

您的 HTML 示例与您显示的代码不匹配,而且您提供的 URL 已不存在,因此很难为您提供帮助。

这是一个开始:

require 'nokogiri'

html = '<div class="zg_usedPrice">
    <a href="http://rads.stackoverflow.com/amzn/click/B000O3GCFU">52&nbsp;new</a>
    </div>
'
doc = Nokogiri::HTML(html)

text = doc.at('div.zg_usedPrice a').text # => "52\u00A0new"
text.gsub(/\u00A0/, ' ') # => "52 new"
于 2014-10-24T22:14:01.093 回答