Clicking link with JavaScript in Mechanize
Asked Answered
C

3

5

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

Cyler answered 20/4, 2012 at 2:18 Comment(0)
W
13

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

Wien answered 20/4, 2012 at 11:17 Comment(0)
V
1

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.

Vent answered 20/4, 2012 at 3:7 Comment(0)
H
0

Here's a way to handle it. Assume your page returns this content:

puts page.body
<HTML><SCRIPT LANGUAGE="JavaScript"><!--
     top.location="http://www.example.com/pages/myaccount/dashboard.aspx?";
// --></SCRIPT>
<NOSCRIPT>Javascript required.</NOSCRIPT></HTML>

We know it's coming so we know what to check for:

link_search = %r{top.location="([^"]+)"}
js_link = page.body.match(link_search)[1]
page = agent.get(js_link)
Hermon answered 2/10, 2013 at 22:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.