如何加快Python中嵌套循环的通过速度

问题描述 投票:0回答:1

如何加速嵌套循环的通过。我正在使用 Selenium 进行浏览器自动化,在代码的一部分中,我需要将系数和日期与表格单元格进行比较。代码绕完整个盘子大约需要 30 秒,大约 6 行 6 列。

    def __parse_full_page(self, url: str, data: dict = {}) -> bool:
        try:
            WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(Locator.PLAN)).click()
            cells = WebDriverWait(self.driver, 10).until(EC.visibility_of_all_elements_located(Locator.CELLS_TABLE))
            current_url = str(self.driver.current_url)
            id_ticket = current_url.split("&")[-2].split("=")[-1]
            button_planning = self.driver.find_element(*Locator.CONFIRM)

            ticket_data = tickets.get(id_ticket)

            if ticket_data != "Заявка не найдена":
                _, max_rate = ticket_data.split(':')
                max_rate = int(max_rate)
            else: max_rate = 0

            coefficients = ["Бесплатно"] + [f'✕{i}' for i in range(1, max_rate + 1)]
            
            for coefficient in coefficients:
                for cell in cells:
                    try:
                        date_text = cell.find_element(*Locator.DATE).text
                        try:
                            date_text_clean = date_text.split(',')[0].strip()
                            date_object = datetime.strptime(date_text_clean, "%d %B")
                            date_object = date_object.replace(year=datetime.now().year)
                        except ValueError as ve:
                            print(f"Ошибка при преобразовании даты: {ve}")
                            continue

                        buffer_days = int(config["BOT"]["BUFFER"])
                        today = datetime.now()
                        buffer_date = today + timedelta(days=buffer_days)

                        if date_object > buffer_date:
                            coefficient_element = cell.find_element(*Locator.RATE)
                            coefficient_text = coefficient_element.text
                            if coefficient_text.strip() == f"{coefficient}":
                                button_hover = cell.find_element(*Locator.CHOOSE_HOVER)
                                self.action.move_to_element(button_hover).perform()
                                try:
                                    cell.find_element(*Locator.CHOOSE).click()
                                    self.action.move_to_element(button_planning).click().perform()
                                    new_id_el = self.driver.find_element(*Locator.ID).text
                                    new_id = new_id_el.strip()
                                    logger.debug("ЗАЯВКА ПРОШЛА")
                                    self.__pretty_log({"id_ticket": id_ticket, 'coefficient': coefficient, 'date': date_text, "new_id": new_id})
                                    return True
                                except Exception as e:
                                    print(f"Ошибка при нажатии 'Выбрать': {e}")
                            else:
                                continue

                        else:
                            continue

                    except Exception as e:
                        print(f"Ошибка: {e}")
                        continue

        except Exception as e:
            print(f"Ошибка: {e}")

        return False


需要加速系数中的系数:对于单元格中的单元格: 循环贯穿WebElement

我不知道如何加快速度。

python loops selenium-webdriver optimization nested-loops
1个回答
0
投票

首先,我会从内部循环中删除这段代码,可能不会有太大帮助,但似乎不需要在那里完成:

buffer_days = int(config["BOT"]["BUFFER"])
      today = datetime.now()
buffer_date = today + timedelta(days=buffer_days)

接下来是基于您所提供的内容而没有亲自测试,您使用的鼠标操作往往很慢:

self.action.move_to_element(button_planning).click().perform()

如果可以通过其他方式完成此操作应该会提高性能(直接单击按钮或使用 JavaScript 执行)。如果你必须有动作链,你可以尝试拆分它,有时效果会更快。

self.action.move_to_element(button_planning).perform()
button_planning.click()
© www.soinside.com 2019 - 2024. All rights reserved.