2964502 2964502 - 6 months ago 36
Python Question

Select check box using Selenium Python

Would be nice if someone know how to select the checkbox using Selenium 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 could not detect what is that???

Answer

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 (1s sleep inbetween).

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 1s.')
        time.sleep(1)
else:
    raise e