Python and Selenium To “execute_script” to solve “ElementNotVisibleException”

前端 未结 2 1938
天涯浪人
天涯浪人 2021-02-06 11:08

I am using Selenium to save a webpage. The content of webpage will change once certain checkbox(s) are clicked. What I want is to click a checkbox then save the page content. (T

2条回答
  •  梦毁少年i
    2021-02-06 11:36

    I had some issues with expected conditions, I prefer building my own timeout.

    import time
    from selenium import webdriver
    from selenium.common.exceptions import \
        NoSuchElementException, \
        WebDriverException
    from selenium.webdriver.common.by import By
    
    b = webdriver.Firefox()
    url = 'the url'
    b.get(url)
    locator_type = By.XPATH
    locator = "//label[contains(text(),' keywords_here')]/../input[@type='checkbox']"
    timeout = 10
    success = False
    wait_until = time.time() + timeout
    while wait_until < time.time():
        try:
            element = b.find_element(locator_type, locator)
            assert element.is_displayed()
            assert element.is_enabled()
            element.click() # or if you really want to use an execute script for it, you can do that here.
            success = True
            break
        except (NoSuchElementException, AssertionError, WebDriverException):
            pass
    if not success:
        error_message = 'Failed to click the thing!'
        print(error_message)
    

    might want to add InvalidElementStateException, and StaleElementReferenceException

提交回复
热议问题