n1c9 n1c9 - 7 months ago 25
Javascript Question

How to target javascript element by it's onclick attribute via Selenium?

I'm working with a webpage that has a number of javascript buttons that are written like this:

<a href="javascript:;" onclick="addtocart('888%20B0007VBRUE%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20',$(this),0)" class="btn btn-lblue pull-right">


Selenium can execute javascript, but I'm not quite sure how to format the javascript query to trigger the individual buy buttons. I tried:

driver.execute_script("document.getElementById("test").onclick = "addtocart('888%20B0007VBRUE%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20',$(this),0)").click()


but this gives me the error
Message: document.getElementById(...) is null
. How can I change what I've tried to get it to work?

Answer

This is because you have not added an id of test to your <a> tag. Also it is generally not advisable to lookup an element based on the value of its onclick handler.

Fixed code:

<a href="javascript:;" id="test" onclick="addtocart('888%20B0007VBRUE%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20',$(this),0)" class="btn btn-lblue pull-right">

In addition, you need to switch one of your " for ' in driver.execute script, because each " terminates the preceding string.

Example:

driver.execute_script('document.getElementById("test"),$(this),0)').click()