如何通过检查是否已在 selenium 中单击来取消选中复选框 python

How to uncheck a checkbox by checking whether it is already clicked or not in selenium python

单击复选框以及如何取消选中该复选框

domestic=driver.find_element_by_xpath('//*[@id="chkGraphic_0"]')
driver.execute_script("arguments[0].click();",domestic)

如果您想先检查复选框是否已选中,请使用 .is_selected():

domestic=driver.find_element_by_xpath('//*[@id="chkGraphic_0"]')
if domestic.is_selected():
    #uncheck
    driver.execute_script("arguments[0].click();",domestic)

使用 execute_script() 并不是为 selecting/deselecting 单击 复选框 的理想方式。相关的 HTML DOM 会帮助我们构建一个规范的答案。但是,对于 select/deselect 一个 checkbox 你需要为 element_to_be_clickable() 引入 WebDriverWait 并且你可以使用以下解决方案:

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#chkGraphic_0"))).click()
    
  • 使用XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='chkGraphic_0']"))).click()
    
  • 注意:您必须添加以下导入:

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