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?
We can select a checkbox either by using the click() method on the input node or on the label node that represents the checkbox. Selenium also offers validation methods like isSelected, isEnabled, and isDisplayed.
is_selected() element method – Selenium Python is_selected method is used to check if element is selected or not. It returns a boolean value True or False.It can be used to check if a checkbox or radio button is selected.
We can check a checkbox in a page in Selenium with the help of click() method. First of all we need to uniquely identify the checkbox with the help of any of the locators like css, xpath, id, class and so on. Next we have to use findElement() method to locate the element and finally perform the clicking action.
Use find_element_by_xpath
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.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
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:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With