0

I am getting my hands on GUI applications, now i am trying to loop using selenium webdriver, but the program doesn't respond once the loop is started. I am using time.sleep because I want to give the site time to load. I already looked up the issue on the internet and now know that with GUI application you shouldn't use time.sleep, but i couldn't find a fix. I read about the .after() method but im not quite sure how to use it. The code:

from selenium import webdriver
import tkinter.font as font
from tkinter import *
import threading
import time


def switch_on():
    # Function for turning the loop on
    global switch
    switch = True
    loop('webdriverpath/chromedriver.exe')


def switch_off():
    # Function for turning the loop off
    global switch
    switch = False


def kill():
    # Function for exiting the program
    time.sleep(0.07)
    root.destroy()


def loop(param):
    def run(param1):
        while switch:
            driver = webdriver.Chrome(param1)
            time.sleep(2) # These time.sleep's cause the issue
            url = 'https://www.example.com/'
            driver.get(url)
            time.sleep(4)
            driver.close()
            time.sleep(4)

    thread = threading.Thread(target=run(param))
    thread.start()


root = Tk()
root.geometry('500x700')
root.resizable(width=False, height=False)
Banner = Label(root, padx=233, pady=20, text='Test', font=myFont)
Banner.grid(row=0, columnspan=5)

# "Start" Button config
start_button = Button(root, width=8, height=1, text="START", bg='#48a868', fg='white', command=switch_on)
start_button.place(x=20, y=80)
# "Stop" Button config
stop_button = Button(root, width=8, height=1, text='STOP', bg='#c75450', fg='white', command=switch_off)
stop_button.place(x=125, y=80)
# "Exit" Button config
kill_button = Button(root, width=8, height=1, text="EXIT", bg='#313641', fg='white', command=kill)
kill_button.place(x=230, y=80)

root.mainloop()
  • If code is running in a separate thread from the Tkinter mainloop, you can freely use `time.sleep()`. However, you didn't succeed in running your code in a separate thread - `target=run(param)` calls `run()` *right now*, in the current thread, and uses its return value (which never arrives, due to the infinite loop) as the actual function to be run in the thread. You need to tell `Thread` what function to call, rather than calling it yourself: `target=run, args=(param,)`. – jasonharper Jul 20 '20 at 00:44

1 Answers1

0

What you're after is driver.implictly_wait()

driver.implicitly_wait(10)

will wait for 10 seconds for a page to appear. Better than time.sleep(10) though, if the page arrives after say, 3 seconds, then it will immediately stop waiting and do the next stuff.

Source: Python & Selenium: Difference between driver.implicitly_wait() and time.sleep()

JimmyCarlos
  • 1,934
  • 1
  • 10
  • 24