Clicking link with JavaScript in Mechanize

user1198316 picture user1198316 · Apr 20, 2012 · Viewed 12.4k times · Source

I have this:

<a class="top_level_active" href="javascript:Submit('menu_home')">Account Summary</a>

I want to click that link but I get an error when using link_to.

I've tried:

bot.click(page.link_with(:href => /menu_home/))
bot.click(page.link_with(:class => 'top_level_active'))
bot.click(page.link_with(:href => /Account Summary/))

The error I get is: NoMethodError: undefined method `[]' for nil:NilClass

Answer

John Douthat picture John Douthat · Apr 20, 2012

That's a javascript link. Mechanize will not be able to click it, since it does not evaluate javascript. Sorry!

Try to find out what happens in your browser when you click that link. Does it create a POST or GET request? What are the parameters that are sent to the server. Once you know that, you can emulate the same action in your Mechanize script. Chrome dev tools / Firebug will help out.

If that doesn't work, try switching to a library that supports javascript evaluation. I've used watir-webdriver to great success, but you could also try out phantomjs, casperjs, pjscrape, or other tools