Home > Software design >  How to click the Checkbox with Selenium and Python
How to click the Checkbox with Selenium and Python

Time:08-13

I am new on selenium and in this case I'm trying build code with selenium python to click checkbox from this HTML:

<div  xpath="1"><input type="checkbox" name="registerPrivacyAgreement" id="registerPrivacyAgreement" value="1"><label for="registerPrivacyAgreement" lang="lang_9" >I acknowledge that my data will be processed in accordance with the <a target="_blank" href="PrivacyPolicy.html">Privacy Policy.</a> &amp; <a target="_blank" href="UserAgreement.html">User Agreement.</a></label></div>

Snapshot of the checkbox:

This Capture From chrome

I already try to click that checkbox from xpath with this code:

driver.find_element(By.XPATH,"/html/body/div[4]/div[1]/div[12]/div/div[4]/input").click()

I also tried by ID, & CSS_Selector but when I run, its doesn't click the checkbox but open newpage about UserAgreement I already try with other way but it always open newpage about UserAgreement not click the checkbox. Then I try with selenium IDE and record after that I play and then its work, but when I copy code from selnium IDE it show like this:

xpath=//div[@id='container']/div/div[12]/div/div[4]/label

Then i try back to my python code and it still open newpage about UserAgreement not click that checkbox. can someone explain me what happen and how to solve that?

Element Snapshot:

Checkbox I want to click

CodePudding user response:

As per the HTML provided:

HTML

To click on the desired ideally you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    driver.execute("get", {'url': 'https://www.toweroffantasy-global.com/'})
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button#onetrust-accept-btn-handler"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.btn>span[lang='loginText'][scaletype]"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.register"))).click()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.checkBox input#registerPrivacyAgreement[name='registerPrivacyAgreement']"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='checkBox']//input[@id='registerPrivacyAgreement']"))).click()
    
  • Note: You have to add the following imports :

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