2013-02-27 78 views
0

我目前有一段代碼,它將獲取產品標題,說明和價格,因此它的效果很好。但是,我也需要它來獲取圖像的URL,這是我的困境。我嘗試在底部的循環內使用xpath,並列出了所有在每個我根本不需要的產品上等於220的圖像。所以基本上我得到這樣的事情....通過nokogiri和xpath解析圖像

產品1標題這裏
產品1只說明這裏
產品1種價格在這裏
http://www.test.com/product1.jpg
http://www.test.com/product2.jpg
http://www.test.com/product3.jpg
http://www.test.com/product4.jpg


產品2標題在這裏
產品2描述在這裏
產品2價格在這裏
http://www.test.com/product1.jpg
http://www.test.com/product2.jpg
http://www.test.com/product3.jpg
http://www.test.com/product4.jpg

在哪裏,我當然希望只是http://www.test.com/product1.jpg和產品2產品1有http://www.test.com/product2.jpg等,等的圖像只是一個div標籤沒有類或ID因此,我爲什麼沒有輕易地把它們放入一個CSS選擇器。我真的是新的ruby/nokogiri所以任何幫助將是偉大的。

require 'nokogiri' 
require 'open-uri' 


url = "http://thewebsitehere" 

data = Nokogiri::HTML(open(url)) 

products = data.css('.item') 



products.each do |product| 
    puts product.at_css('.vproduct_list_title').text.strip 
    puts product.at_css('.vproduct_list_descr').text.strip 
    puts product.at_css('.price-value').text.strip 
    puts product.xpath('//img[@width = 220]/@src').map {|a| a.value } 

end 
+0

如果您不包含您要解析的HTML,我們無法幫到您。 – 2013-02-27 19:38:59

回答

2

嘗試改變:

puts product.xpath('//img[@width = 220]/@src').map {|a| a.value } 

到:

puts product.xpath('.//img[@width = 220]/@src').map {|a| a.value } 

'。'的點。可以說你想要所有圖像是當前節點的子節點(例如,所以你不會偷看產品2的圖像)。

+0

太棒了!這樣做,謝謝一個男人。 – critic 2013-02-27 19:45:00

0

File#basename將只返回文件名:

File.basename('http://www.test.com/product4.jpg') 
#=> "product4.jpg" 

所以,你可能想是這樣的:

puts product.xpath('//img[@width = 220]/@src').map {|a| File.basename(a.value) } 
+0

啊,對不起,也許我沒有足夠清楚地解釋我的情況。實際上,我不希望每個不同產品上的整個頁面的所有不同產品圖像。我想產品1有http://www.test.com/product1.jpg和產品2有http://www.test.com/product2.jpg我不希望產品2有http:// www .test.com/product1.jpg http://www.test.com/product2.jpg http://www.test.com/product3.jpg http://www.test.com/product4.jpg 如果這樣做更有意義。我編輯了我的原始帖子,以幫助澄清。感謝那tid位,雖然,很高興知道。 – critic 2013-02-27 19:35:24