如何在Python中使用RobotFramework SeleniumLibrary使用JavaScript点击一个WebElement?

问题描述 投票:0回答:1

我试图使用JavaScript点击一个WebElement,但我无法为此创建一个JavaScript语句。

我可以点击一个 取消 按钮,使用此语句

driver.execute_javascript("$(\"div[title='Cancel']\")[0].click()")

但在点击另一个更复杂的元素时,我尝试这样做

expand_xpath = "//span[text()='Submit']//ancestor::table//a[text()='Expand']"
driver.execute_javascript("document.getElementByXpath('${expand_xpath}').click()")

JavascriptException: 消息:javascript错误:document.getElementByXpath不是一个函数。

这个 expand_xpath 储存了我需要点击的WebElement的xpath,但我无法为点击这个元素编写JS代码。

请找到RobotFramework 执行Javascript 此链接上的关键词说明https:/robotframework.orgSeleniumLibrarySeleniumLibrary.html#Execute%20Javascript。

第二次尝试。

expand_xpath = "//span[text()='Submit']//ancestor::table//a[text()='Expand']"
driver.execute_javascript("document.evaluate('${expand_xpath}', document.body, null, 9, null).singleNodeValue.click()")

输出:

JavascriptException: Message: javascript error: missing ) after argument list
python selenium robotframework
1个回答
1
投票

尝试使用下面的javaScript点击元素。

 element= driver.find_element_by_xpath("//span[text()='Submit']//ancestor::table//a[text()='Expand']")
 driver.execute_script("arguments[0].click();", element)

或者使用下面的语句。

expand_xpath = "//span[text()='Submit']//ancestor::table//a[text()='Expand']"
driver.execute_javascript("document.getElementByXPath('${expand_xpath}').click()")

注意:"P "是大写的。XPath.


0
投票

由于你使用的是RobotFramework,这个很简单。

${locator}    //button[@id='abc']
Execute JavaScript    document.evaluate("${locator}", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.click()

注意输入的xpath不能包含双引号(")字符,只能是单引号('),以防止JS解析错误。


0
投票

我是用这个方法来处理点击的。

Arguments:ele_xpath : 要点击的元素的XPATH。

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))
© www.soinside.com 2019 - 2024. All rights reserved.