使用 Selenium Python 是否存在 verify/assert 元素 CheckBox 的任何选项

Is there any option to verify/assert element CheckBox is present using Selenium Python

我正在尝试验证复选框是否存在,但没有找到确切的答案是否可以使用 Selenium Python(断言将是很好的解决方案)进行检查。

这是我的代码:

driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div[1]').click()
time.sleep(1)
driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div[1]/div/div/div[1]/div/ul/li[2]').click()

现在我需要验证元素是否具有 xpath:

/html/body/div[2]/div/div/div[2]/div[1]/div/div/div[1]/div/ul/li[2]

存在还是不存在?

如果你想检查对象的状态,你可以使用is_selected()函数。

driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[2]/div/div[1]').is_selected()

要验证复选框是否理想地存在,您需要引入 WebDriverWait for the and you can use either of the following :

  • 使用XPATH:

    element = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "/html/body/div[2]/div/div/div[2]/div[1]/div/div/div[1]/div/ul/li[2]")))
    
  • 注意:您必须添加以下导入:

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