我尝试单击带有硒的html标签,但出现错误。
如何获取硒以单击此类标记?
我已经尝试过此代码,但出现错误:
driver.find_element_by_id("btnCreateJE").click()
HTML代码:
<a id="btnCreateJE" data-permission="true" onclick="NewManualJE()" href="@" class="btn waves-effect waves-light"> New </a>
Python硒代码:
driver.find_element_by_id("btnCreateJE").click()
我收到该错误:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="btnCreateJE"]"}
(Session info: chrome=75.0.3770.142)
答案 0 :(得分:2)
链接可能不会立即出现在DOM中,也就是说,稍后会由于AJAX调用而添加链接。如果是这种情况,请考虑添加Explicit Wait,例如:
WebDriverWait(driver, 10).until(expected_conditions.presence_of_element_located((By.ID, "btnCreateJE"))).click()
答案 1 :(得分:2)
所需元素是启用了JavaScript的元素,因此对元素click()
进行PARTIAL_LINK_TEXT
诱使 WebDriverWait 以便使元素可点击您可以使用以下任一解决方案:
使用WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "New"))).click()
:
CSS_SELECTOR
使用WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.btn.waves-effect.waves-light#btnCreateJE[onclick^='NewManualJE']"))).click()
:
XPATH
使用WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='btn waves-effect waves-light' and @id='btnCreateJE'][starts-with(@onclick, 'NewManualJE')]"))).click()
:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
注意:您必须添加以下导入:
country_mapping = {
'Germany': 'germany_depreciation.xlsx',
'France': 'france_depreciation.xlsx',
# other countries
}