简体   繁体   中英

How do I stop a selenium script while it's running in python and then start it again from the begining?

The issue I'm having is that when I stop the script with driver.close(), I can't start over the script because the instance is tied to the first attempt. Is there a way to start a new instance? I'm using Tkinter to start and stop the selenium script.

    from tkinter import *
    from tkinter.ttk import *
    from SeleniumBot import SeleniumBot
    import threading
    
    root = Tk()
    root.title("SelBot")
    
    # Title of the program
    label = Label(text="SelBot")
    
    text = Text(root, height=5, width=52)
    loadbar = Progressbar(root, orient=HORIZONTAL, length=300, mode='indeterminate')
    s = SeleniumBot()
    
    
    def startBot():
        loadbar.start()
        text.insert(INSERT, 'Bot has started!\n')
        t1 = threading.Thread(target=sBot())
        t1.start()
    
    
    
    def sBot():
        s.login()
        text.insert(INSERT, 'Log In Complete-----------1/3\n')
        s.search()
        text.insert(INSERT, 'Search Complete-----------2/3\n')
        s.complete()
        text.insert(INSERT, 'Task Completed------------3/3\n')
        loadbar.stop()
    
    
    def endBot():
        text.insert(INSERT, 'Bot has stopped!\n')
        s.botStop()
        loadbar.stop()
    
    startBtn = Button(root, text="Start", command=startBot)
    stopBtn = Button(root, text="Stop", command=endBot)
    
    label.pack()
    startBtn.pack()
    stopBtn.pack()
    loadbar.pack()
    text.pack()
    
    root.mainloop()

The solution I came up with to solve my problem was to put the selenium bot in a list. It's probably not the best solution but it gets the job done for what I want. My reasoning for using a list is that when the stop button is clicked I can stop the selenium bot, then remove it and start a new instance. And when I click the start button it will use the new instance.

botList = [SeleniumBot()]


def startBot():
    loadbar.start()
    text.insert(INSERT, 'Bot has started!\n')
    t1 = threading.Thread(target=sBot)
    t1.start()



def sBot():
    botList[0].login()
    text.insert(INSERT, 'Log In Complete-----------1/3\n')
    botList[0].search()
    text.insert(INSERT, 'Search Complete-----------2/3\n')
    botList[0].complete()
    text.insert(INSERT, 'Task Completed------------3/3\n')
    loadbar.stop()


def endBot():
    text.insert(INSERT, 'Bot has stopped!\n')
    botList[0].botStop()
    botList.pop(0)
    botList.append(SeleniumBot())
    loadbar.stop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM