How to use Thread in my project with Tkinter and Selenium

Asked

Viewed 147 times

1

I’m making a bot to get the free books that Amazon made available, so I created a graphical interface, but after discovering that Tkinter does not work the way I wanted, it also stops working when running Selenium.

I looked for help and found the solution of using threads to make such application, however, after being able to use both without locking, it occurred of not working the progress bar nor the function of informing how many books were taken, someone knows how to help?


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import random
from tkinter import *
import tkinter.messagebox
from tkinter import ttk
from _thread import *

class StoreBooks:
    def __init__(self):
        self.caughtbooks = 0
        self.pagspassed = 0



class   AMZBot():
    def __init__(self, username, password, url, code):
        self.username = username
        self.password = password
        self.url = url
        self.code = code
        self.a = 0
        firefoxProfile = webdriver.FirefoxProfile()
        firefoxProfile.set_preference("int1.accept_languages", "pt,pt-BR")
        firefoxProfile.set_preference("dom.webnotifications.enable", False)
        self.driver = webdriver.Firefox(
            firefox_profile=firefoxProfile, executable_path=r"C:\Users\User\Desktop\Gecko\geckodriver.exe"
        )

    def login(self,):
        try:

            driver = self.driver
            driver.get("https://www.amazon.com.br/ap/signin?openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.com.br%2Fref%3Dnav_signin&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.assoc_handle=brflex&openid.mode=checkid_setup&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&")
            loginusuario = driver.find_element_by_xpath("//input[@name='email']")
            loginusuario.clear()
            loginusuario.send_keys(self.username)
            buto = driver.find_element_by_id('continue').click()
            passwd = driver.find_element_by_xpath( "//input[@name='password']")
            passwd.clear()
            passwd.send_keys(self.password)
            time.sleep(2)
            buton = driver.find_element_by_id('signInSubmit').click()
            time.sleep(2)
        except:
            time.sleep(60)
        try:
            buton = driver.find_element_by_id('continue').click()
            time.sleep(30)
        except:
            pass

        self.takebooks()

    def takebooks(self):
        driver = self.driver
        driver.get(self.url)
        time.sleep(1)
        store = StoreBooks()
        while True:
            for n in range(1,1000):

                try:
                    clicar = driver.find_element_by_id('a-autoid-'+str(n)+'-announce').send_keys(Keys.SHIFT + Keys.CONTROL + Keys.ENTER)
                    store.caughtbooks += 1
                    print("Livro Pego({})".format(store.caughtbooks))
                    time.sleep(0.5)
                    driver.switch_to_window(driver.window_handles[-1])
                    time.sleep(1)
                    driver.close()
                    driver.switch_to_window(driver.window_handles[0])
                    time.sleep(1)
                except Exception as error:
                    #print("----")
                    pass
            try:

                nextpage = driver.find_element_by_class_name('a-last').click()
                store.pagspassed += 1
            except Exception as error:
                print(error)

            time.sleep(3)


def main():
    root = Tk()
    app = Window1(root)
    root.mainloop()
class Window1():
    def __init__(self, master):
        self.master = master
        self.master.title("BotInstagtram")
        self.master.geometry("700x500")
        self.frame = Frame(self.master)
        self.frame.pack()
        self.user = StringVar()
        self.passwd = StringVar()
        self.url = StringVar()
        self.LabelTitle = Label(self.frame, text="BOT AMAZON FREE BOOKS", font=("verdana", 30), bd=20, justify=LEFT)
        self.LabelTitle.grid(row=0, columnspan=2, pady=20, sticky=W)
        #-----------------------------------------------------------
        #Frames
        self.Loginframe1 = Frame(self.frame, width=500, height=150, bd=20, relief='ridge')
        self.Loginframe1.grid(row=1, column=0, sticky=W)
        self.Loginframe2 = Frame(self.frame, width=500, height=50, bd=10, relief='ridge')
        self.Loginframe2.grid(row=2, column=0, sticky=W)
        self.Loginframe3 = Frame(self.frame, width=500, height=50, bd=10, relief='ridge')
        self.Loginframe3.grid(row=3, column=0, sticky=W)

        ##########################################
        #Bar
        self.var_bar = DoubleVar()
        self.my_bar = ttk.Progressbar(self.Loginframe3, variable=self.var_bar, maximum=400, mode="determinate", length=310)
        self.my_bar.grid()

        #-----------------------------------------------------------
        #StringVar
        self.url.set('https://www.amazon.com.br/s?i=digital-text&bbn=5475882011&rh=n%3A5308307011%2Cn%3A5308308011%2Cn%3A5475882011%2Cp_36%3A5560478011%2Cp_n_feature_browse-bin%3A6406077011&dc&language=pt_BR&_encoding=UTF8&fst=as%3Aoff&linkCode=sl2&linkId=c74a3b3b1606b3a2c5d5249ccab38e13&primeCampaignId=prime_assoc_ft&qid=1591627747&rnid=6406076011&tag=ynv-20&ref=sr_nr_p_n_feature_browse-bin_2')
        self.code = StringVar()
        #-----------------------------------------------------------
        #Frame1
        self.LabelUser = Label(self.Loginframe1, text="Nome", font=('arial', 15, "bold"))
        self.LabelUser.grid()
        self.LabeltxtUser = Entry(self.Loginframe1, text="Nome", font=('arial', 15, "bold"), textvariable=self.user)
        self.LabeltxtUser.grid(row=0, column=1)
        self.LabelPasswd = Label(self.Loginframe1, text="Senha", font=('arial', 15, "bold"))
        self.LabelPasswd.grid(row=1, column=0)
        self.LabeltxtPasswd = Entry(self.Loginframe1, text="Senha", font=('arial', 15, "bold"), show="*", textvariable=self.passwd)
        self.LabeltxtPasswd.grid(row=1, column=1)
        self.Botar = Label(self.Loginframe1, text="URL", font=('arial', 12, 'bold'))
        self.Botar.grid(row=2, column=0)
        self.LabeltxtURL = Entry(self.Loginframe1, text="URL", font=('arial', 15, "bold"), textvariable=self.url)
        self.LabeltxtURL.grid(row=2, column=1)
        #self.Botarcode = Label(self.Loginframe1, text="Code", font=('arial', 12, 'bold'))
        #self.Botarcode.grid(row=3, column=0)
        #self.Labeltxtcode = Entry(self.Loginframe1, text="Codigo", font=('arial', 15, "bold"), textvariable=self.code)
        #self.Labeltxtcode.grid(row=3, column=1)

        #-----------------------------------------------------------
        #Frame2

        self.TestarConta = Button(self.Loginframe2, text="Executar", width=10, font=('arial', 12, 'bold'), command=self.ThreandingBooks)
        self.TestarConta.grid()
        #-----------------------------------------------------------
        #Frame3
        self.duvida = Button(self.Loginframe2, text="?", width=6, font=('arial', 12, 'bold'), command=self.show_books_and_pages)
        self.duvida.grid(row=0, column=1)


    def show_books_and_pages(self):
        store = StoreBooks()
        tkinter.messagebox.showinfo("Info", "Book: {}\n Pages:{}".format(store.caughtbooks, store.caughtbooks))

    def ThreandingBooks(self):
        start_new_thread(self.Login, (1,))

    def update(self):
        tkinter.messagebox.showinfo("Caught Books", )
        self.master.after(1, self.showCaughtBooks)


    def showCaughtBooks(self):
        store = StoreBooks()
        while True:
            if self.var_bar.get() <400:
                self.var_bar.set(self.store.pagspassed)
                self.master.update()
                self.master.after(15000, store.showCaughtBooks)
                time.sleep(1)

            else:
                return False



    def Login(self, nada):
        nada =0
        name = (self.user.get())
        passwd = (self.passwd.get())
        url = (self.url.get())
        code = self.code
        self.jansen = AMZBot(name, passwd, url, code)
        self.jansen.login()
        self.update()



if __name__ == '__main__':
    main()

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.