我有这个类
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
谢谢。
最佳答案
这将返回该图像作为 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">]>
这将返回源网址
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 方法调用它。
编辑 向您的用户显示这将在 rails View 中工作的所有图像
<% @page.images.each do |image| %>
<%= image_tag(image.url) %>
<% end %>
这将遍历所有图像并将它们显示在页面中的图像标签中。显然,这可能需要修改,具体取决于 url 是相对的还是完整的。
老实说除非你需要
mechanize
设置cookies或其他东西我会看看Nokogiri
.不是 100% 确定如何使用 Mechanize 来做到这一点,而是使用 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
关于ruby-on-rails - 使用 Mechanize 从 url 获取相关内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22233337/