点击按钮id与Python Selenium



我有以下HTML代码从"accept-cookie"窗口:

<div id="_name-buttons"> 
<button id="_name-preferences">[...]</button> 
<button id="_name-accept">[...]</button>

我正在尝试使用Selenium点击按钮_name-accept,即接受cookie。我的代码做了以下工作:

from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
...
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, '_name-accept'))).click()

但是它不工作,我有这个错误:

selenium.common.exceptions.TimeoutException: Message: 
Stacktrace:
WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:183:5
NoSuchElementError@chrome://remote/content/shared/webdriver/Errors.jsm:395:5
element.find/</<@chrome://remote/content/marionette/element.js:300:16

我如何点击按钮id?谢谢你

代替点击元素id您可以使用以下任意定位器策略:

使用
  • CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div#_name-buttons button#_name-accept"))).click()
    
  • 使用<<li>em> XPATH :

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='_name-buttons']//button[@id='_name-accept']"))).click()
    

最新更新