dilbert
dilbert

Reputation: 3098

Unable to execute javascript in onclick using selenium

Using selenium (with python bindings), I'm dealing with a webpage that is almost entirely AJAX; including hyperlinks. Instead of using the element.click() method, I wish to execute the javascript in the "onclick" attribute of the tag:

The tag:

<a onclick="javascript:setEvent(event);requisition_openRequisitionDescription('requisitionListInterface','actOpenRequisitionDescription',_ftl_api.lstVal('requisitionListInterface', 'requisitionListInterface.listRequisition', 'requisitionListInterface.d327682e687', this),'requisitionList');return ftlUtil_followLink(this);" href="#" title="View this job description" id="requisitionListInterface.reqTitleLinkAction.row1">

The code:

from selenium import webdriver
firefox = webdriver.Firefox()
firefox.get("some_url")
elem = firefox.find_element_by_id("requisitionListInterface.reqTitleLinkAction.row1")
jcode = elem.get_attribute("onclick")
firefox.execute_script(jcode)

The Error:

WebDriverException: Message: u'event is not defined' ; Stacktrace:

Disclaimer:

I don't understand Javascript. As far as I can tell, it's expecting the 'event' variable, however I guess it has something to do with a callback ?

EDIT:

I've assumed that the javascript is modifying the href attribute but is it possible for javascript to redirect the browser without modifying the hyperlink?

Upvotes: 0

Views: 8093

Answers (3)

Trinh Truong
Trinh Truong

Reputation: 151

from selenium.webdriver.common.action_chains import ActionChains
firefox = webdriver.Firefox()
# You need a mouse to hover the span elements here, and please try this way :)
self.mouse = webdriver.ActionChains(firefox)    

# You need get the span element from its xpath:
elem = firefox.find_element_by_id("requisitionListInterface.reqTitleLinkAction.row1")

# Then you hover on span element by mouse and click on it:
self.mouse.move_to_element(elem).click().perform()

Upvotes: 0

cegprakash
cegprakash

Reputation: 3125

You can just click it using this.

elem.click()

The onclick event will automatically get triggered.

Upvotes: 4

Vengarioth
Vengarioth

Reputation: 684

Unless selenium does something crazy, which i doubt, onclick="javascript:setEvent(event) is not valid javascript. the rest of the string however is. When this code block gets executed, it tries to invoke a function called setEvent with the variable event, which remains undefined.

<a onclick="requisition_openRequisitionDescription('requisitionListInterface','actOpenRequisitionDescription',_ftl_api.lstVal('requisitionListInterface', 'requisitionListInterface.listRequisition', 'requisitionListInterface.d327682e687', this),'requisitionList');return ftlUtil_followLink(this);" href="#" title="View this job description" id="requisitionListInterface.reqTitleLinkAction.row1">

since event is nowhere else needed in your script, just remove it?

Upvotes: 0

Related Questions