【问题标题】:How can I detect a new blog post using mechanize in ruby如何在 ruby​​ 中使用 mechanize 检测新博客文章
【发布时间】:2023-03-19 11:14:01
【问题描述】:

我正在尝试检测新博客文章何时添加到博客。我正在使用机械化进行刮擦。目前,如果您知道博客<article><header><h1>Blot Title here</h1></header></article> 的父标签,那么这很简单,您可以将您现在拥有的标题与上次检查时的标题进行比较。但我想以编程方式执行此操作。有没有办法以编程方式知道页面的哪个部分或标签包含博客文章的标题,而无需明确地为脚本提供标签的层次结构?

【问题讨论】:

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


    【解决方案1】:

    假设有一个博客名称 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 gem 的例子。它从 www.eslemployment.com 收集工作。现在您的问题是如何检测新文章已添加。

    此代码收集页面中的所有作业并将其添加到数据库中。我在这里使用“distint”代码到模型中,因此只有新作业才会添加到数据库中。不会将复制作业添加到数据库中。添加新作业时,您可以通知添加了哪个作业。

    这不是有效的方法。但它会起作用。否则,您可以使用该博客的 RSS 提要。这是检测新帖子的正确方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多