(Python)我该如何解决这个问题?每次重复我的功能时,我都需要一个计数器

Posted

技术标签:

【中文标题】(Python)我该如何解决这个问题?每次重复我的功能时,我都需要一个计数器【英文标题】:(PYTHON) How do I solve this? I need a counter for each time my function is repeated 【发布时间】:2022-01-19 20:26:00 【问题描述】:

我是 python 新手,我正在为我的项目构建代码,我需要每次 iniciobot() 函数重复,它是 计数并显示在我的 tkinter 屏幕上。我尝试使用全局变量 contagem 来执行此操作,但没有任何反应。 我该如何解决这个问题?如果有人可以帮助我,我感激不尽


电话来了

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()

【问题讨论】:

请不要用葡萄牙语在这里发帖。选择一种语言,然后在适当的网站上发布:这里是英语,Stack Overflow em Português 上是葡萄牙语。 你确定你调用了这个函数吗?至少我没有看到它被调用。 使用装饰器。 ***.com/questions/44968004/… @bichanna 是的,该函数是在 tkinter 上的按钮上调用的 tkinter 之外的一个简单测试对我有用。 【参考方案1】:

处理这类“我需要添加一些东西”到函数的最佳方法是使用 python 装饰器。由于 Python 中的所有内容都是对象,而且函数也是对象,因此您可以将函数传递给函数并用一些新功能有效地包装它......在这种情况下是调用计数器。

我已经评论了回答这个问题的链接,但我会在这里再次发布:python-decorators-count-function-call

由于您是这里的新发帖者,我将通过添加一些有用的 cmets 来回顾一下代码中发生的情况:

"""                                                                                                                                                                                                               
# 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

【讨论】:

Eu testei usando decorator como você informou. mas acabo recebendo um TypeError dizendo (TypeError: iniciobot() missing 1 required positional argument: 'anumber') 我解决了TypeError问题,不知道是不是最合适。我刚刚从“def iniciobot(anumber)”中取出 (anumber),只留下“def iniciobot(*args, **kwargs) 并且它起作用了。代码@count_my_calls def iniciobot(*args, **kwargs):”这里有一些代码”

以上是关于(Python)我该如何解决这个问题?每次重复我的功能时,我都需要一个计数器的主要内容,如果未能解决你的问题,请参考以下文章

maven安装时出现编译错误我该如何解决这个错误[重复]

为啥我的工具输出会覆盖自身,我该如何解决?

类型错误,我该如何解决这个错误,在图片中我写了我的具体问题

我该如何解决这个问题:Illuminate\Contracts\Container\BindingResolutionException 目标类 [HomeController] 不存在 [重复]

我该如何解决这个问题。我正在尝试使用 len 功能,但它没有按预期工作 [重复]

我该如何解决? 在Python?