rails机械化.click#的未定义方法`click'

时间:2018-07-30 22:16:53

标签: ruby-on-rails mechanize

我已经在Rails中创建了一个机械化任务。这很简单

task :estimateone => :environment do
  require 'mechanize'

  mechanize = Mechanize.new
  page = mechanize.get('https://www.theurbanlist.com/brisbane/a-list/50-brisbane-cafes-you-should-have-eaten-breakfast-at')
  page.css('ol li a').each do |link|
    link.click
  end

end

但是我收到此错误,我在做什么错了?

rake aborted!
NoMethodError: undefined method `click' for #<Nokogiri::XML::Element:0x00007ffb4b281830>
/Users/jeremybray/RubymineProjects/OpportunityFinder/lib/tasks/getlead.rake:8:in `block (2 levels) in <top (required)>'
/Users/jeremybray/.rvm/gems/ruby-2.4.2/gems/nokogiri-1.8.4/lib/nokogiri/xml/node_set.rb:204:in `block in each'
/Users/jeremybray/.rvm/gems/ruby-2.4.2/gems/nokogiri-1.8.4/lib/nokogiri/xml/node_set.rb:203:in `upto'
/Users/jeremybray/.rvm/gems/ruby-2.4.2/gems/nokogiri-1.8.4/lib/nokogiri/xml/node_set.rb:203:in `each'
/Users/jeremybray/RubymineProjects/OpportunityFinder/lib/tasks/getlead.rake:7:in `block in <top (required)>'
/Users/jeremybray/.rvm/gems/ruby-2.4.2@global/gems/rake-12.3.1/exe/rake:27:in `<top (required)>'
/Users/jeremybray/.rvm/gems/ruby-2.4.2/bin/ruby_executable_hooks:15:in `eval'
/Users/jeremybray/.rvm/gems/ruby-2.4.2/bin/ruby_executable_hooks:15:in `<main>'

2 个答案:

答案 0 :(得分:1)

由于click是Mechanize的一种方法,因此应将其实例用作click方法的接收者,而不是链接,它是Nokogiri的链接。

按照doc的说明,它接收元素,单击它并返回获取的页面。

尝试:

-- snip --
page.css('ol li a').each do |link|
  mechanize.click(link)
end

答案 1 :(得分:1)

Page#links_with将返回链接,css将返回html元素:

page.links_with(css: 'ol li a').each do |link|
  link.click
end