2014-03-06 30 views
1

我有這個類獲取revlant內容從URL與機械化

class Scrapper 
    require 'rubygems' 
    require 'mechanize' 

    def initialize(url) 
     @url = url 
     agent = Mechanize.new 
     @page = agent.get(url) 
    end 

    def perform(type) 
     if type == 'title' 
      get_title 
     else 
      get_content 
     end 
    end 

    def get_title 
     @page.title 
    end 

    def get_content 
     @page 
    end 
end 

現在,我可以得到網頁的標題,但我如何得到的相關內容?
例如http://thenextweb.com/facebook/2014/03/06/facebook-launches-improved-version-major-news-feed-redesign-teased-last-year/#!yJE5N

  • 我想獲得一個蓋/任何相關圖片(如有)。
  • 頁面內容。
    謝謝。
+0

您對相關的定義看起來與此相關......請看看[Nokogiri](http://nokogiri.org/),其中機械化是建立在此基礎之上的。 – engineersmnky

+0

Relevnant圖像,例如該文章的封面圖片。 – Saff

回答

2

這將返回圖像作爲Nokogiri::XML::Element

def get_article_image_tag 
    @page.at(".article-featured-image > img") 
end 
#=> #<Nokogiri::XML::Element:0x19ac280 name="img" attributes= #<Nokogiri::XML::Attr:0x19ac238 name="width" value="786">, #<Nokogiri::XML::Attr:0x19ac22c name="height" value="305">, #<Nokogiri::XML::Attr:0x19ac 220 name="src" value="http://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2014/03 187265573-786x305.jpg">, #<Nokogiri::XML::Attr:0x19ac214 name="class" value="attachment-featured_post wp-post-image">, #<Nokogiri::XML::Attr:0x19ac208 name="alt" value="SWEDEN-FACEBOOK-DATA-CENTER-SERVERS">, #<Nokogiri::XML::Attr:0x19ac1fc name="title" value="Facebook launches an improved version of the News Feed redesign teased last year">]> 

這將返回源URL

def get_article_image_src 
    @page.at(".article-featured-image > img").attributes["src"].value 
end 
#=>"http://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2014/03/187265573-786x305.jpg" 

爲了讓文章全文

def get_article_text 
    @page.at("div.article").text 
end 

這將返回沒有任何格式的文章文本只是文本和不可見字符,如\n,\t等。此方法似乎也在選擇器內部刮取HTML/Javascript代碼。

也爲動態能力,你可以改變這裏您的通話

def perform(type) 
    self.send("get_#{type.to_s}") 
end 

那麼它可以與任何的「內容」,「標題」,「article_image_tag」,「article_image_src」和任何其他get_xxx方法,你可以叫定義。

編輯顯示您的用戶這一切將在軌運行圖像查看

<% @page.images.each do |image| %> 
    <%= image_tag(image.url) %> 
<% end %> 

這將通過所有的圖像進行迭代,並在頁面中的圖片標籤顯示它們。顯然這可能需要修補,取決於網址是相對還是完整。

老實說,除非你需要mechanize設置cookie或什麼我會看看Nokogiri。不是100%確定如何做到這一點機械化,但與Nokogiri你可以通過它的整體大小確定一個圖片的「相關性」。

require 'nokogiri' 
require 'open-uri' 

doc = Nokogiri::HTML(open("http://thenextweb.com/facebook/2014/03/06/facebook-launches-improved-version-major-news-feed-redesign-teased-last-year/#!yJ6uM")) 
largest_image = doc.search("img").sort_by{|image| image.attributes["height"].value.to_i * image.attributes["width"].value.to_i}.pop 
+0

非常感謝您的幫助,但如果是另一個網址呢?我試圖通過讓用戶輸入網址並將其返回到圖像+文本內容來將其添加到我的網站。 – Saff

+0

Ohhh yhh。這正是我想要的。我會試試Nokogiri並回到yu。 Thankksss :) – Saff