Select checkbox using Selenium with Python
Asked Answered
A

8

43

How can I select the checkbox using Selenium with Python?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()
url = 'Any URL'
browser.get(url)

browser.find_element_by_id("15 Minute Stream Flow Data: USGS (FIFE)").click()

I want to select the checkbox corresponding to 15 Minute Stream Flow Data: USGS (FIFE).

I tried as id, name, link_text, but I could not detect it. What should be used?

Altis answered 19/1, 2014 at 5:5 Comment(0)
E
32

Use find_element with the XPath expression .//*[contains(text(), 'txt')] to find a element that contains txt as text.

browser.find_element(By.XPATH, 
    ".//*[contains(text(), '15 Minute Stream Flow Data: USGS (FIFE)')]"
).click()

UPDATE

Some contents are loaded after document load. I modified the code to try 10 times (1 second sleep in between).

import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException

browser = webdriver.Firefox()
url = 'http://reverb.echo.nasa.gov/reverb/'
browser.get(url)

for i in range(10):
    try:
        browser.find_element(By.XPATH,
            ".//*[contains(text(), '15 Minute Stream Flow Data: USGS (FIFE)')]"
        ).click()
        break
    except NoSuchElementException as e:
        print('Retry in 1 second')
        time.sleep(1)
else:
    raise e
Esthonia answered 19/1, 2014 at 5:15 Comment(8)
sorry to tell you that your code is not working in my PC. @EsthoniaAltis
whoops! i am using windows 7 64bit python 3.2, selenium 2.39 @EsthoniaAltis
@viena, I've just test the same code with Python 3.4.0b2, selenium 2.39, and it just worked. BTW, what do you mean it is not working? Does the code cause error? No error, but nothing happended?Esthonia
@viena, What error do you get? selenium.common.exceptions.NoSuchElementException ?Esthonia
yes, with python 3.2 64bit i got raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: 'Unable to locate element: {"method":"xpath","selector":".//*[contains(text(), \'15 Minute Stream Flow Data: USGS (FIFE)\')]"}' @falstruAltis
@viena, What you do get if you execute print(browser.current_url) (just after browser.get(url) statement).Esthonia
i obtained reverb.echo.nasa.gov/reverb/… @EsthoniaAltis
@viena, You can also use Waits. Check out the documentation.Esthonia
H
10

The checkbox HTML is:

<input id="C179003030-ORNL_DAAC-box" name="catalog_item_ids[]" type="checkbox" value="C179003030-ORNL_DAAC">

so you can use

browser.find_element_by_id("C179003030-ORNL_DAAC-box").click()

One way you can find elements' attributes is using the Google Chrome Developer Tools:

Inspect element

Homomorphism answered 19/1, 2014 at 5:8 Comment(1)
your code also works given that Waits is used as provided by falsetruAltis
D
10

You can try in this way as well:

browser.find_element_by_xpath(".//*[@id='C179003030-ORNL_DAAC-box']")

If you want know if it's already checked or not:

browser.find_element_by_xpath(".//*[@id='C179003030-ORNL_DAAC-box']").get_attribute('checked')

to click:

browser.find_element_by_xpath(".//*[@id='C179003030-ORNL_DAAC-box']").click()
Dipeptide answered 17/5, 2016 at 14:26 Comment(1)
.get_attribute() is very useful!! ThanksMonney
R
1

This is the best approach to click by using Selenium Python:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()

url = 'Any URL'
browser.get(url)

box = browser.find_element_by_xpath("paste the XPath expression here")
browser.execute_script("arguments[0].click();", box)
Ransdell answered 4/11, 2019 at 3:38 Comment(1)
I agree, I also use this approach.Sheedy
W
1

Here's one way to select/click the checkbox with a complete solution.

this is the website , for example.

and let's say this is the desired checkbox on the given website (marked under red loop) to perform a click.

solution:

import time
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import selenium.webdriver.support.expected_conditions as EC

driver = Chrome()
driver.get('https://register.whirlpool.com/en-us/registration')

WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, 'privacy_policy')))
driver.execute_script("document.getElementById('privacy_policy').click();")
time.sleep(2)
var1 = driver.find_element(By.ID, "privacy_policy").is_selected()
print(var1)

output:

True
  1. First, we wait and locate the element By the available methods(here By.ID) to make sure that the target checkbox element is loaded/located on the page.
  2. Next, execute the javascript query (here document.getElementById('privacy_policy').click()) to click on the checkbox.
  3. We can also verify if the click or the select was performed on the desired checkbox using the method is_selected() as mentioned above.
  4. It'll return True if the checkbox was clicked/selected and False otherwise.

You can also cross-check by simply running the javascript query document.getElementById('privacy_policy').click() on the Console of the page and you'll see that it indeed performs the click on the desired checkbox.

Watthour answered 5/6, 2023 at 8:56 Comment(0)
H
0

You can try this as well:

browser = webdriver.Firefox()
url = 'http://reverb.echo.nasa.gov/reverb/'
browser.get(url)
browser.find_element_by_name("catalog_item_ids[]").click()
Handknit answered 2/1, 2017 at 12:19 Comment(0)
B
0

The best way to handle the element "Checkbox" if it has text is to use a JavaScript function to extract it from the webpage:

For example: //*[text()='text on element']

Here also you can use the same while extracting the checkbox and use the click() function to check it.

driver = webdriver.Chrome()
url = "URl of site"
driver.get(url)
checkbox = driver.find_element_by_xpath(//*[text()='text on element'])
checkbox.click()

To check whether an element got checked or not, you may use the get_attribute() function.

For example: checkbox.get_attribute('checked')

Bisutun answered 19/8, 2020 at 8:22 Comment(0)
M
0

I recommend reading this

https://splinter.readthedocs.io/en/latest/api/driver-and-element-api.html?highlight=radio#splinter.driver.DriverAPI.choose

browser.check("checkbox_name")
Madlin answered 9/11, 2021 at 17:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.