2013-05-09 82 views
0

我構建了一個刮板來從維基百科表中提取所有信息並將其上傳到我的數據庫。一直都很好,直到我意識到我在圖像上拉錯了URL,並且我想要實際的圖像URL「http://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Baconbutty.jpg」,而不是它容易給我的「/wiki/File:Baconbutty.jpg」。這是我到目前爲止的代碼:如何從此Wikipedia表格中提取正確的圖片網址?

def initialize 
    @url = "http://en.wikipedia.org/wiki/List_of_sandwiches" 
    @nodes = Nokogiri::HTML(open(@url)) 
end 

def summary 

    sammich_data = @nodes 

    sammiches = sammich_data.css('div.mw-content-ltr table.wikitable tr') 
    sammich_data.search('sup').remove 

    sammich_hashes = sammiches.map {|x| 

     if content = x.css('td')[0] 
     name = content.text 
     end 
     if content = x.css('td a.image').map {|link| link ['href']} 
     image =content[0] 
     end 
     if content = x.css('td')[2] 
     origin = content.text 
     end 
     if content = x.css('td')[3] 
     description =content.text 
     end 

我的問題是這一行:

if content = x.css('td a.image').map {|link| link ['href']} 
      image =content[0] 

如果我去td a.image img,它只是給我一個null條目。

有什麼建議嗎?

+0

你也在刮維基百科而不是使用它的API,這會讓你的生活更加艱難。 – 2013-05-09 17:40:01

回答

1

以下是我會做(如果我是湊百川,有容我不會因爲他們確實有這個東西的API):它輸出

require 'nokogiri' 
require 'open-uri' 
require 'pp' 

doc = Nokogiri::HTML(open("http://en.wikipedia.org/wiki/List_of_sandwiches")) 

sammich_hashes = doc.css('table.wikitable tr').map { |tr| 
    name, image, origin, description = tr.css('td,th') 
    name, origin, description = [name, origin, description].map{ |n| n && n.text ? n.text : nil } 
    image = image.at('img')['src'] rescue nil 

    { 
    name: name, 
    origin: origin, 
    description: description, 
    image: image 
    } 
} 

pp sammich_hashes 

[ 
    {:name=>"Name", :origin=>"Origin", :description=>"Description", :image=>nil}, 
    { 
    :name=>"Bacon", 
    :origin=>"United Kingdom", 
    :description=>"Often served with ketchup or brown sauce", 
    :image=>"//upload.wikimedia.org/wikipedia/commons/thumb/3/38/Baconbutty.jpg/120px-Baconbutty.jpg" 
    }, 
    ... [lots removed] ... 
{ 
    :name=>"Zapiekanka", 
    :origin=>"Poland", 
    :description=>"A halved baguette or other bread usually topped with mushrooms and cheese, ham or other meats, and vegetables", 
    :image=>"//upload.wikimedia.org/wikipedia/commons/thumb/1/12/Zapiekanka_3..jpg/120px-Zapiekanka_3..jpg" 
    } 
] 

如果圖像不可用,則該字段將在返回的散列值中設置爲nil

+0

謝謝!我沒有意識到API,但老實說,這仍然是一個很好的教訓。 – DynastySS 2013-05-09 21:44:08

0

您可以使用img元素的srcset屬性對其進行拆分並保留其中一個可用的調整大小的圖像。

if content = x.at_css('td a.image img') 
    image =content['srcset'].split(' 1.5x,').first