How can I select the checkbox using Selenium with Python?
from selenium import webdriver
from selenium.webdriver.common.keys import Keysbrowser = 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?
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 timefrom selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementExceptionbrowser = 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()breakexcept NoSuchElementException as e:print('Retry in 1 second')time.sleep(1)
else:raise e