Select checkbox using Selenium with Python

后端 未结 6 1856
鱼传尺愫
鱼传尺愫 2020-12-25 10:45

How can I select the checkbox using Selenium with Python?

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

browser = webdriver.         


        
6条回答
  •  醉梦人生
    2020-12-25 11:27

    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
    

提交回复
热议问题