我想在Python上使用Selenium单击一个按钮(事件),并且按钮代码为:
<input id="workbenchLst:j_id_id509" name="workbenchLst:j_id_id509" onclick="A4J.AJAX.Submit('workbenchLst',event,{'similarityGroupingId':'workbenchLst:j_id_id509','parameters':{'ajaxSingle':'workbenchLst:j_id_id509','workbenchLst:j_id_id509':'workbenchLst:j_id_id509'} ,'containerId':'j_id_id1'} );return false;" value="Add" type="button" autocomplete="off">
我的代码:
driver.find_element_by_id("workbenchLst:j_id_id509").click()#add
它不起作用,错误:
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [name="workbenchLst:j_id_id509"]
答案 0 :(得分:0)
所需元素是动态元素,因此要定位该元素,必须使 WebDriverWait 成为可点击的 元素,并且可以使用以下任一解决方案:
使用CSS_SELECTOR
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[id^='workbenchLst:'][name^='workbenchLst:'][value='Add']"))).click()
使用XPATH
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[starts-with(@id,'workbenchLst:') and starts-with(@name,'workbenchLst:')][@value='Add']"))).click()
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
答案 1 :(得分:0)
首先检查页面中的iframe /框架,如果有一个框架/ iframe,则需要先切换框架,如下所示:
driver.switch_to_frame(driver.find_element_by_id("iframeid"));
您可以尝试使用以下XPath单击该元素:
element = driver.find_element_by_xpath("//input[contains(@id, 'workbenchLst') and @value='Add']");
element.click();
或者您可以尝试使用JavaScript Executor,如下所示:
element = driver.find_element_by_xpath("//input[contains(@id, 'workbenchLst') and @value='Add']");
driver.execute_script("arguments[0].click();", element);
仍然无法正常工作,然后尝试延迟一下,从如下所示的时间导入睡眠:
from time import sleep
driver.switch_to_frame(driver.find_element_by_id("iframeid"));
sleep(5);
element = driver.find_element_by_xpath("(//input[contains(@id, 'workbenchLst') and @value='Add'])[2]");
element.click();
我希望它能起作用...
答案 2 :(得分:-1)
尝试:
element = driver.find_element_by_id('workbenchLst:j_id_id509')
element.click()
或:
element = driver.find_element(by=By.ID, value="workbenchLst:j_id_id509")