Farzan Ali Khan
Farzan Ali Khan

Reputation: 3

How do I click on this check box using selenium

I would like to select this checkbox using selenium

<input type="checkbox" name="rg" onchange="onCheckReg(this)" id="beauty_perfume_screening__c" value="beauty_perfume_screening__c" tabindex="-1" aria-labelledby="check-button-Beauty Perfume Screening check-group-header">

I tried finding by xpath an by id but always get the error unable to locate element

wd.find_element_by_id("beauty_perfume_screening__c").click()

Any Ideas?

Upvotes: 0

Views: 98

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193088

To click on the element with text as save you can use either of the following Locator Strategies:

  • Using id:

    wd.find_element_by_id("beauty_perfume_screening__c").click()
    
  • Using css_selector:

    wd.find_element_by_css_selector("input#beauty_perfume_screening__c[name='rg'][value='beauty_perfume_screening__c']").click()
    
  • Using xpath:

    wd.find_element_by_xpath("//input[@id='beauty_perfume_screening__c' and @name='rg'][@value='beauty_perfume_screening__c']").click()
    

Ideally, to click on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • Using ID:

    WebDriverWait(wd, 20).until(EC.element_to_be_clickable((By.ID, "beauty_perfume_screening__c"))).click()
    
  • Using CSS_SELECTOR:

    WebDriverWait(wd, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#beauty_perfume_screening__c[name='rg'][value='beauty_perfume_screening__c']"))).click()
    
  • Using XPATH:

    WebDriverWait(wd, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='beauty_perfume_screening__c' and @name='rg'][@value='beauty_perfume_screening__c']"))).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
    

Important: Incase the element is within an <iframe> you have to switch to the <iframe> first.

You can find a couple of relevant discussions in:


References

You can find a couple of relevant discussions on NoSuchElementException in:

Upvotes: 0

Dev
Dev

Reputation: 2813

Use xpath

driver.find_element_by_xpath("//input[@name='rg']").click()

and recommended is to use one of the wait methods -

WebDriverWait(driver, 10).until(
    EC.presence_of_element_located(By.XPATH, "//input[@name='rg']")

For selecting iframe -

root1 = driver.find_element_by_xpath("//iframe")
driver.switch_to.frame(root1)

enter image description here

Upvotes: 1

Related Questions