Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking link with JavaScript in Mechanize

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

like image 722
user1198316 Avatar asked Apr 20 '12 02:04

user1198316


2 Answers

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

like image 93
John Douthat Avatar answered Sep 28 '22 23:09

John Douthat


The first 2 should have worked so try this, print out the hrefs to make sure it's really there:

puts page.links.map(&:href)

Remember that just because you can see it in your browser does not mean it appears in the response. It could have been sent as an ajax update. Also you can just do this which I think is cleaner:

page.link_with(:href => /menu_home/).click

However I don't think clicking that link will do what you want since it's javascript.

like image 29
pguardiario Avatar answered Sep 29 '22 00:09

pguardiario