0

I'm new to python, I'm building code for my project and I need that every time my iniciobot() function is repeated, it's counted and shown on my tkinter screen. I tried to do it using a global variable contagem, but nothing happens. How do I solve this? If anyone can help me I appreciate it.


here is the call

botao2 = Button(janela, text='Anunciar', image=foto2, 
style='W.TButton', command=iniciobot)
botao2.pack(side=TOP)

contagem = 0


def iniciobot():
    global contagem
    contagem += 1
    class InitBot1v:  # a partir dessa classe pode começar a repetição
        for InitBot1v in range(3):
            driver.get('https://conta.olx.com.br/anuncios/publicados')
            time.sleep(3)
            driver.find_element_by_xpath('//*[@id="main-page-content"]/div[1]/div[1]/header/div[3]/div[2]/a').click()
            try:
                element = WebDriverWait(driver, 15).until(
                    ec.presence_of_element_located((By.XPATH, '//*[@id="input_subject"]'))
                )
            finally:
                driver.find_element_by_xpath('//*[@id="input_subject"]').send_keys(random.choice(olxlist.lista_compras))
                driver.find_element_by_xpath('//*[@id="input_body"]').send_keys(olxdescricao.lista_venda)
                driver.find_element_by_xpath('//*[@id="category_item-1000"]').click()
                driver.find_element_by_xpath('//*[@id="category_item-1100"]').click()
                time.sleep(2)
                driver.find_element_by_xpath(
                    '//*[@id="root"]/div[3]/form/div[1]/div/div[1]/div[3]/div[1]/div/div[1]/label/span').click()
                driver.find_element_by_xpath('//*[@id="size"]').send_keys('1000')
                driver.find_element_by_xpath('//*[@id="re_land_type"]').click()
                driver.find_element_by_xpath('//*[@id="re_land_type"]/option[2]').click()
                driver.find_element_by_xpath('//*[@id="price"]').send_keys('40000')

                time.sleep(4)

                pyautogui.click(1380, 447)  # 1600x900 - x,y (1380, 447) click na tela da olx para fazer scroll
                pyautogui.scroll(-2000)
                time.sleep(2)

                class pegar_pasta:
                    pyautogui.click(89,
                                    879)  # click no gerenciador de arquivos para ir na foto 1600x900 - x,y (89, 879)
                    time.sleep(0.2)
                    pyautogui.click(269,
                                    801)  # click na foto para fazer a seleção e os dois 'down' aqui dbaixo é pra n repetir as fotos 1600x900 - x,y (269, 801)
                    pyautogui.keyDown('down')
                    pyautogui.keyDown('down')
                    time.sleep(0.1)
                    pyautogui.keyDown('Shift')  # segurar para selecionar as 3 fotos
                    time.sleep(0.5)
                    pyautogui.keyDown('down')  # esses 2 'down' é pra selecionar as fotos
                    pyautogui.keyDown('down')
                    pyautogui.keyUp('Shift')  # soltar o shift da seleção das fotos

                    time.sleep(1)

                    class enviar_foto:
                        pyautogui.mouseDown()
                        pyautogui.moveTo(212, 879)  # 1600x900 - x,y (212, 879)
                        time.sleep(0.5)
                        pyautogui.moveTo(212, 870, 0.2)  # 1600x900 - x,y (212, 870, 0.2)
                        time.sleep(0.2)
                        pyautogui.moveTo(190, 231, 1)  # 1600x900 - x,y (190, 231, 1)
                        time.sleep(0.2)
                        pyautogui.mouseUp()
                        time.sleep(0.2)
                        driver.find_element_by_xpath('//*[@id="zipcode"]').send_keys(random.choice(olxcep.lista_cep))
                        time.sleep(0.3)
                        driver.find_element_by_xpath('//*[@id="ad_insertion_submit_button"]').click()
                        time.sleep(3)
                        driver.find_element_by_xpath('//*[@id="ad_insertion_submit_button"]').click()
                        time.sleep(10)


def mostrar_quantidade():
    print(contagem)


janela = Tk()

janela.configure(border=40, background='white')
janela.title('Olx Bot Anúncio')


texto_espaco = Label(janela, text=contagem)
texto_espaco.pack(side=TOP)


janela.mainloop()

1 Answers1

1

The best way to handle these sorts of "I need to add something" to a function is to use the python decorator. Since everything in python is an object, and because functions are objects too, you can pass a function to a function and effectively wrap it up with some new feature... in this case a call counter.

I already commented the link to where this question was answered, but I'll post it again here: python-decorators-count-function-call

Since you're a new poster here, I'll go over what's going on here in the code by adding some useful comments:

"""                                                                                                                                                                                                               
# Here you define a function that takes a function as an argument... as well as                                                                                                                                   
# the *args and **kwargs "Magic" that will call your inner fuction correctly no                                                                                                                                   
# matter how it's invoked.                                                                                                                                                                                        
"""                                                                                                                                                                                                               
def count_my_calls(func, *args, **kwargs):
    """
    # This call_counter function is your new fuction.  When you use a decorator
    # you're creating a new fuction that wraps the old one up with some new
    # feature... in this case a counter
    """
    def call_counter(*args, **kwargs):
        """
        # When you call your original function after decorating it this is where
        # your code will end up.  So, here it looks like we're adding 1 to an
        # uninitilized memeber of call_counter, but we haven't actually executed
        # this code yet.
        """
        call_counter.count += 1
        """
        # This is a debug print statement to show off your count
        """
        print(call_counter.count)
        """
        # This is where you are callinging the function that was passed to
        # count_my_calls.  This will call the function with the arguments.
        """
        return func(*args, **kwargs)
    """
    # This is where you initilize the member variable in the call_counter
    # function.  This code is executed when the decorator in envoked below with
    # the @call_counter statement
    """
    call_counter.count = 0
    """
    # you are here returning the function you've just created, but you don't
    # have to do anything else with it, it'll be covered by the decorator
    # syntax
    """
    return call_counter


"""                                                                                                                                                                                                               
# Now, in order to use your new decorator to turn **ANY FUNCTION** into one
# that counts how many times it's been called, use the @decorator syntax:
"""
@count_my_calls
def say_hi(name):
    print("Hello {}".format(name))



# And, behold the fruits of your labor:                                                                                                                                                                           
say_hi('Joe')
#1
#Hello Joe

say_hi('Jim')
#2
#Hello Jim

say_hi("steve")
#3
#Hello steve

print say_hi.count
#3
VoNWooDSoN
  • 1,173
  • 9
  • 13
  • Eu testei usando decorator como você informou. mas acabo recebendo um TypeError dizendo (TypeError: iniciobot() missing 1 required positional argument: 'anumber') – BOB CÃOMUNISTA Dec 21 '21 at 00:20
  • I solved the TypeError problem, I don't know if it was the most appropriate. I just took the (anumber) from my "def iniciobot(anumber)" and left only "def iniciobot(*args, **kwargs) and it worked. The code @count_my_calls def iniciobot(*args, **kwargs): "some code here" – BOB CÃOMUNISTA Dec 21 '21 at 01:15