1

*编辑:根据我下面的评论,我想一个更好的问题是,'让 mechanize 遍历每个 url 并更新其名称列的正确方法是什么?(每个名称对于 url 来说都是唯一的)' 下面是我练习的基础。*


我有一个 postgres 表,类似于... | 名称(字符串)| 网址(文本)|

url 列已经填充了各种 url,看起来像这样: http ://www.a4apps.com/Websites/SampleCalendar/tabid/89/ctl/Register/Default.aspx

我正在尝试运行一个 mechanize rake 任务,该任务将通过每个 url 运行并根据它在 css 标记处找到的文本更新名称。

namespace :db do
  desc "Fetch css from db urls"
  task :fetch_css => :environment do

    require 'rubygems'
    require 'mechanize'
    require 'open-uri'

    agent = Mechanize.new
    url = Mytable.pluck(:url)
    agent.get(url)
    agent.page.search('#dnn_ctr444_ContentPane').each do |item|
      name = item.css('.EventNextPrev:nth-child(1) a').text
      Mytable.update(:name => name)
    end 
  end
end

当我运行 rake 任务时,它返回:

rake aborted!
bad URI(is not URI?): %255B%2522http://www.a4apps.com/Websites/SampleCalendar/tabid/89/Default.aspx%2522,%2520%2522http://www.a4apps.com/Websites/SampleCalendar/tabid/89/ctl/Privacy/Default.aspx%2522,%2520%2522http://www.a4apps.com/Websites/SampleCalendar/tabid/89/ctl/Terms/Default.aspx%2522,%2520%2522http://www.a4apps.com/Websites/SampleCalendar/tabid/89/ctl/Register/Default.aspx%2522%255D

谢谢你的帮助。如果有什么方法可以让问题更容易回答,请告诉我。麦克风

4

1 回答 1

1

我最近在回答自己的问题时感到有点孤独,但如果其他人发现自己处于同样的困境中,我会发布我的答案。另外,也许其他人会告诉我我的解决方案是否有我还没有看到的致命缺陷。这是我最后的 rake 似乎正在工作,从我的表中获取 url,在它们上运行 mechanize 并使用在 url 中找到的信息更新表......

namespace :db do
  desc "Fetch css from db urls"
  task :fetch_css => :environment do

    Mytable.all.each do |info|  # for each row do...
      require 'rubygems'
      require 'mechanize'
      require 'open-uri'
      agent = Mechanize.new
      agent.get(info.url)             # get the url column data for the current db row...
      nombre = agent.page.search('.EventNextPrev:nth-child(1) a').text  # plug it into mech.
      info.update_attributes(:name => nombre)  # and update the db with the css result.
    end

  end
end

谢谢。麦克风

于 2012-11-09T14:01:59.177 回答