How to click link in Mechanize and Nokogiri?

老子叫甜甜 提交于 2019-12-04 10:15:37

click is a method of Mechanize class.

Try following form.

next_page = @orders_page.at("#purchaseOrderPager-pagerNextButton")
mechanize_instance.click(next_page)

NOTE Replace mechanize_instance with actual variable.

Your one doesn't work, as #search gives Nokogiri::XML::NodeSet instance. NodeSet is a collection of nodes. But in your case it is next_page is a NodeSet collection, which holds only one element. And first will give you the Nokogiri::XML::Node, which is also an Nokogiri::XML::Element.

Write as below :

next_page = @orders_page.search("#purchaseOrderPager-pagerNextButton").first

Or better to use #at method.

next_page = @orders_page.at("#purchaseOrderPager-pagerNextButton")

Now #click is a method of Mechanize::Page::Link instance. Open the source :

# File lib/mechanize/page/link.rb, line 29
def click
  @mech.click self
end

Here is the full code :-

next_page = @orders_page.at("#purchaseOrderPager-pagerNextButton")
# mech is your Mechanize object.
next_link = Mechanize::Page::Link.new( next_page, mech, @orders_page )
next_link.click

Mechanize#click lets you supply a string with the text of the anchor/ button to click on and Nokogiri::XML::Node as well. So we can do :

mech.click next_page

Let's see why the above code would work :

source code lines

  referer = current_page()
  href = link.respond_to?(:href) ? link.href :
    (link['href'] || link['src'])
  get href, [], referer
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!