How can I make Selenium/Python wait for the user to login before continuing to run?

前端 未结 2 1355
Happy的楠姐
Happy的楠姐 2020-12-17 21:18

I\'m trying to run a script in Selenium/Python that requires logins at different points before the rest of the script can run. Is there any way for me to tell the script to

2条回答
  •  無奈伤痛
    2020-12-17 21:52

    Use WebDriverWait. For example, this performs a google search and then waits for a certain element to be present before printing the result:

    import contextlib
    import selenium.webdriver as webdriver
    import selenium.webdriver.support.ui as ui
    with contextlib.closing(webdriver.Firefox()) as driver:
        driver.get('http://www.google.com')
        wait = ui.WebDriverWait(driver, 10) # timeout after 10 seconds
        inputElement = driver.find_element_by_name('q')
        inputElement.send_keys('python')
        inputElement.submit()
        results = wait.until(lambda driver: driver.find_elements_by_class_name('g'))
        for result in results:
            print(result.text)
            print('-'*80)
    

    wait.until will either return the result of the lambda function, or a selenium.common.exceptions.TimeoutException if the lambda function continues to return a Falsey value after 10 seconds.

    You can find a little more information on WebDriverWait in the Selenium book.

提交回复
热议问题