Search code examples
pythonseleniumflasktimeoutexception

Selenium TimeoutException with Flask and Python


This is what my code looks like

@app.route("/Committ", methods=['GET', 'POST']) 
def Committ():
  ......
  if(......):
    #do sthg
    firefox_profile = webdriver.FirefoxProfile()
    firefox_profile.set_preference("browser.priavtebrowsing.autostart",True)
    driver = webdriver.Firefox(firefox_profile = firefox_profile)
    driver.get("https://www.instagram.com")
    assert "Instagram" in driver.title
    ......
    driver.close()

After running the code above for a number a time usually at the 2nd or third time I get the following error: condtion 1

I try add a try and except to avoid this from happening but it didn't rly workout.

UnboundLocalError


Solution

  • So it turned out to be a minor issue to cause the whole thing to fall apart, where when flask navigates to a page is like calling a function, everything would goes away when it leaves the page. However selenium always makes internal changes, thus I didn't properly closed the driver when I leave the function causing confusion when the function got called again!

    This is what I originally have:

    ...do sthg...
    return redirect(url_for('home'))
    driver.close()
    

    A simple fix would be

    ...do sthg...
    driver.close()
    return redirect(url_for('home'))