Reputation:
I'm trying to click on a WebElement using JavaScript but I'm unable to create a JavaScript statement for that.
I'm able to click on a Cancel button using this statement
driver.execute_javascript("$(\"div[title='Cancel']\")[0].click()")
But on clicking another element which is more complicated, I'm trying this
expand_xpath = "//span[text()='Submit']//ancestor::table//a[text()='Expand']"
driver.execute_javascript("document.getElementByXpath('${expand_xpath}').click()")
JavascriptException: Message: javascript error: document.getElementByXpath is not a function
This expand_xpath is storing xpath of the WebElement which I need to click but I'm unable to frame the JS code for clicking this element.
Please find the RobotFramework Execute Javascript keyword expnation on this link https://robotframework.org/SeleniumLibrary/SeleniumLibrary.html#Execute%20Javascript
Second Try:
expand_xpath = "//span[text()='Submit']//ancestor::table//a[text()='Expand']"
driver.execute_javascript("document.evaluate('${expand_xpath}', document.body, null, 9, null).singleNodeValue.click()")
Output:
JavascriptException: Message: javascript error: missing ) after argument list
Upvotes: 0
Views: 1063
Reputation:
I'm using this method to deal with the click.
Arguments: ele_xpath : XPATH of the element to be clicked.
from SeleniumLibrary import SeleniumLibrary
def click_element_with_javascript(ele_xpath):
try:
js_exp = "document.evaluate(\"##xpath##\", document.body, null, 9, null).singleNodeValue.click()".replace('##xpath##', ele_xpath)
driver.execute_javascript(js_exp)
except Exception as e:
print("Element click through javascript resulted in Exception: {}".format(e))
Upvotes: 0
Reputation: 394
Since you're using RobotFramework, this one is quite easy:
${locator} //button[@id='abc']
Execute JavaScript document.evaluate("${locator}", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.click()
Note that the inputted xpath should not contain double quote (") character, only single quote (') to prevent JS parsing error
Upvotes: 0
Reputation: 816
Try clicking on element using below javaScript :
element= driver.find_element_by_xpath("//span[text()='Submit']//ancestor::table//a[text()='Expand']")
driver.execute_script("arguments[0].click();", element)
OR use below:
expand_xpath = "//span[text()='Submit']//ancestor::table//a[text()='Expand']"
driver.execute_javascript("document.getElementByXPath('${expand_xpath}').click()")
Note: "P" is in uppercase in XPath.
Upvotes: 1