2013-05-09 35 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