等待然后单击一个项目?

Wait for and then click an item?

所以我想等待弹出窗口,然后单击“接受”。 HTML 看起来像这样:

<div class="termsBtn" onclick="checkTerms(0)" style="background-color:#dd4a42">Decline</div>

<div class="termsBtn" onclick="checkTerms(1)" style="background-color:#a6dd42">Accept</div>


我已经尝试了各种方法,但是对于当前代码,我得到了 TimeoutException:

selenium.common.exceptions.TimeoutException: Message: 



我现在的代码:

from selenium.webdriver.support import expected_conditions as ec


wait = WebDriverWait(driver, 10)
popup = wait.until(ec.element_to_be_clickable((By.XPATH, '//input[@onclick="checkTerms(1)"]')))
popup.click()

您的元素没有输入标签,它是 xpath 下的 div tag.Try。

wait = WebDriverWait(driver, 10)
popup = wait.until(ec.element_to_be_clickable((By.XPATH, '//div[@class="termsBtn"][text()="Accept"]')))
popup.click()

你可以使用ExpectedConditions.visibilityOfElementLocated,它会等到元素不可见

来源:

Webdriver How to wait until the element is clickable in webdriver C#

由于所需的元素在弹出窗口中,因此要在元素上 click(),您必须为 element_to_be_clickable() 引入 WebDriverWait,您可以使用以下解决方案之一:

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.termsBtn[onclick*='1']"))).click()
    
  • 使用XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='termsBtn' and text()='Accept']"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC