如何在ruby中使用mechanize检测新的博客帖子

时间:2015-01-31 10:19:31

标签: ruby-on-rails ruby screen-scraping mechanize blogs

我正在尝试检测何时将新博客帖子添加到博客中。我正在使用机械化进行刮擦。目前,如果您知道博客<article><header><h1>Blot Title here</h1></header></article>的父标签,您可以直接进行上次检查时所拥有的标题差异。但我想以编程方式执行此操作。有没有办法以编程方式知道包含博客帖子标题的页面的哪个部分或标签,而没有明确地给标记提供标签?

1 个答案:

答案 0 :(得分:0)

假设有一个博客名称blog.example.com。有帖子 -

<article><header><h1>Blot Title here1</h1></header></article>
<article><header><h1>Blot Title here2</h1></header></article>
<article><header><h1>Blot Title here3</h1></header></article>

使用selector Gaget,您将了解哪个css负责每篇文章。要废弃该文章,您可以使用nokogiri或machanize gem。

假设macanize bot将访问blog.example.com,它将收集所有文章并插入到您的数据库中。

require 'nokogiri'
require 'open-uri'
if 1==1
url = "http://www.eslemployment.com/country/esl-jobs-Vietnam.html"
doc = Nokogiri::HTML(open(url))
data = []
doc.css("#joblist td:nth-child(1) a").first(5).each do |titlecss|
country = "8"
jobtype = "1"
urlnext = titlecss.attr('href')
docnext = Nokogiri::HTML(open(urlnext))
docnext.css('#jobdescription div').remove
docnext.css('#detailjob , #job-summary').each do |detailscss|
docnext.css('#pagemsg h1').each do |titlenextcss|
data << JobPost.create(
:title => titlenextcss.text,
:jobslink => urlnext,
:description => detailscss.inner_html,
:country_id => country,
:job_type_id => jobtype
)
end
end
end
end

这是nokogiri宝石的一个例子。它从www.eslemployment.com收集工作。现在您的问题是如何检测到新文章已添加。

此代码从页面收集所有作业并将其添加到数据库中。我在这里使用&#34; distint&#34;因此,代码进入模型只会将新作业添加到数据库中。没有重复作业将添加到数据库中。添加新作业后,您可以发出添加作业的通知。

这不是有效的方式。但它会奏效。否则,您可以使用该博客的RSS订阅源。这是检测新帖子的正确方法。