Оптимизируй этот код   from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import ElementNotVisibleException, NoSuchElementException
import time
import datetime
import sys

def Page_navigation(kol_click):
    try:
        n_click = 1
        while n_click <= kol_click:
            element_next = wait.until(
                EC.element_to_be_clickable((By.XPATH, '//div[@class="pagination-next"]/a[@class="paginator-elem"]'))
            )
            element_next.click()
            time.sleep(3)
            element = wait.until(
                EC.visibility_of_element_located((By.XPATH, '//label[@class="input-label"]'))
            )
            n_click += 1

    except Exception:
        with open(FILENAME, 'a', encoding='cp1251') as f:
            print('Класс ошибки =>', sys.exc_info()[0], file=f)
            print('Наименование ошибки =>', sys.exc_info()[1], file=f)
            print('№ строки с ошибкой в исходном коде Python =>', sys.exc_info()[2].tb_lineno, file=f)
            print('', file=f)
            f.close()

def Page_100_zapisei():
    try:
        element_spisok = wait.until(
            EC.element_to_be_clickable(
                (By.XPATH, '//div[@class="ngx-select__toggle btn form-control form-control-sm input-sm btn-sm"]'))
        )
        element_spisok.click()
        time.sleep(3.0)
        element_100_pages = wait.until(
            EC.element_to_be_clickable((By.XPATH, '//ul[@class="ngx-select__choices dropdown-menu show"]/li[4]/a'))
        )
        element_100_pages.click()
        element = wait.until(
            EC.element_to_be_clickable(
                (By.XPATH, '//div[@class="ngx-select__toggle btn form-control form-control-sm input-sm btn-sm"]'))
        )
        time.sleep(3.0)
    except Exception:
        with open(FILENAME, 'a', encoding='cp1251') as f:
            print('Класс ошибки =>', sys.exc_info()[0], file=f)
            print('Наименование ошибки =>', sys.exc_info()[1], file=f)
            print('№ строки с ошибкой в исходном коде Python =>', sys.exc_info()[2].tb_lineno, file=f)
            print('', file=f)
            f.close()

def Page_100_zapisei_N2():
    try:
        element_spisok = wait.until(
            EC.element_to_be_clickable(
                (By.XPATH, '//div[@class="ngx-select__toggle btn form-control form-control-sm input-sm btn-sm"]'))
        )
        element_spisok.click()
        time.sleep(3.0)
        element_100_pages = wait.until(
            EC.element_to_be_clickable(
                (By.XPATH, '//ul[@class="ngx-select__choices dropdown-menu ng-star-inserted show"]/li[4]/a'))
        )
        element_100_pages.click()
        element = wait.until(
            EC.element_to_be_clickable(
                (By.XPATH, '//div[@class="ngx-select__toggle btn form-control form-control-sm input-sm btn-sm"]'))
        )
        time.sleep(3.0)
    except Exception:
        with open(FILENAME, 'a', encoding='cp1251') as f:
            print('Класс ошибки =>', sys.exc_info()[0], file=f)
            print('Наименование ошибки =>', sys.exc_info()[1], file=f)
            print('№ строки с ошибкой в исходном коде Python =>', sys.exc_info()[2].tb_lineno, file=f)
            print('', file=f)
            f.close()

FILENAME = "Лог работы скрипта.txt"
dt = datetime.datetime.now()

with open(FILENAME, 'w', encoding='cp1251') as f:
    print('Дата и время начала работы скрипта ->', dt.strftime("%d.%m.%Y г.  время: %H:%M:%S"), file=f)
    print('', file=f)
f.close()

Spis_users = "Список пользователей с Гoсуслуг.txt"
with open(Spis_users, 'w', encoding='cp1251') as sp_users:
    sp_users.close()

options = webdriver.ChromeOptions()
binary_yandex_driver_file = 'D:\\PROGRAMS\\Yandexdriver\\yandexdriver.exe'
service = Service(executable_path=binary_yandex_driver_file)
browser = webdriver.Chrome(service=service, options=options)
browser.maximize_window()
browser.get("https://esia.gosuslugi.ru/profile/org/1000300363/branch/1020660440/emps")

wait = WebDriverWait(browser, 180, poll_frequency=1, ignored_exceptions=[ElementNotVisibleException, NoSuchElementException])

try:
    element = wait.until(
        EC.visibility_of_element_located((By.XPATH, '//input[@id="login"]'))
    )
    with open(FILENAME, 'a', encoding='cp1251') as f:
        print('Элемент для ввода логина найден', file=f)
        print('', file=f)
        f.close()

except Exception:
    with open(FILENAME, 'a', encoding='cp1251') as f:
        print('Класс ошибки =>', sys.exc_info()[0], file=f)
        print('Наименование ошибки =>', sys.exc_info()[1], file=f)
        print('№ строки с ошибкой в исходном коде Python =>', sys.exc_info()[2].tb_lineno, file=f)
        print('', file=f)
        f.close()
else:
    element.click()
    time.sleep(3)
    element.send_keys('moi-login')
    time.sleep(3)

try:
    element = wait.until(
        EC.visibility_of_element_located((By.XPATH, '//input[@id="password"]'))
    )
    with open(FILENAME, 'a', encoding='cp1251') as f:
        print('Элемент для ввода пароля найден', file=f)
        print('', file=f)
        f.close()
except Exception:
    with open(FILENAME, 'a', encoding='cp1251') as f:
        print('Класс ошибки =>', sys.exc_info()[0], file=f)
        print('Наименование ошибки =>', sys.exc_info()[1], file=f)
        print('№ строки с ошибкой в исходном коде Python =>', sys.exc_info()[2].tb_lineno, file=f)
        print('', file=f)
        f.close()
else:
    element.click()
    time.sleep(3)
    element.send_keys('AAAAA')
    time.sleep(3)

try:
    element = wait.until(
        EC.element_to_be_clickable((By.XPATH, '//button[@class="plain-button plain-button_wide"]'))
    )
    time.sleep(1)
    with open(FILENAME, 'a', encoding='cp1251') as f:
        print('Кнопка «ВОЙТИ» доступна для клика по ней', file=f)
        print('', file=f)
        f.close()

except Exception:
    with open(FILENAME, 'a', encoding='cp1251') as f:
        print('Класс ошибки =>', sys.exc_info()[0], file=f)
        print('Наименование ошибки =>', sys.exc_info()[1], file=f)
        print('№ строки с ошибкой в исходном коде Python =>', sys.exc_info()[2].tb_lineno, file=f)
        print('', file=f)
        f.close()
else:
    element.click()

Page_100_zapisei()

N_Page = 1
Npp = 0
vihod = False

try:
    element_next = wait.until(
        EC.element_to_be_clickable((By.XPATH, '//a[@class="paginator-elem current"]'))
    )
    found_elem_next = True
    N_zapr = 1

except Exception:
    with open(FILENAME, 'a', encoding='cp1251') as f:
        print('Класс ошибки =>', sys.exc_info()[0], file=f)
        print('Наименование ошибки =>', sys.exc_info()[1], file=f)
        print('№ строки с ошибкой в исходном коде Python =>', sys.exc_info()[2].tb_lineno, file=f)
        print('', file=f)
        f.close()
else:
    while vihod == False:
        time.sleep(1)
        if N_zapr == 1:
            elements = browser.find_elements(By.XPATH, '//li[@class="item row"]')
            N_zapr = N_zapr + 1
        else:
            elements = browser.find_elements(By.XPATH, '//li[@class="item row ng-star-inserted"]')

        print("№ страницы =>", N_Page, "  Всего элементов на странице =>", len(elements))
        i = 0
        while i < len(elements):
            try:
                Npp += 1
                fio = elements[i].find_element(By.XPATH, './/b')
                dolgn = elements[i].find_element(By.XPATH, './/span[1]')
                tel = elements[i].find_element(By.XPATH, './/span[2]')
                email = elements[i].find_element(By.XPATH, './/span[3]')
                gr_dost = elements[i].find_element(By.XPATH, './/span[4]')
                web_adr = elements[i].find_element(By.XPATH, './/div[1]/p/a').get_attribute('href')

                with open(Spis_users, 'a', encoding='cp1251') as sp_users:
                    print("№ сраницы", N_Page, "   № п/п", Npp, "   ", fio.text)
                    print(fio.text, file=sp_users)
                    print(dolgn.text, file=sp_users)
                    print(tel.text, file=sp_users)
                    print(email.text, file=sp_users)
                    print(web_adr, file=sp_users)
                    print(gr_dost.text, file=sp_users)
                    sp_users.close()

                ssilka = elements[i].find_element(By.XPATH, './/span[4]/a').click()
                element_kontrol1 = wait.until(
                    EC.visibility_of_element_located((By.XPATH, '//div/h2[@class="title access-group-title"]'))
                )
                time.sleep(3)
                gis_elements = browser.find_elements(By.XPATH, '//div[@class="access-group ng-star-inserted"]')
                j = 0
                gis_i_roli = ''
                while j < len(gis_elements):
                    gis = gis_elements[j].find_element(By.XPATH, './/div[@class="col span_12 push_1 system"]')
                    gis_i_roli = gis.text
                    roli = browser.find_elements(By.XPATH, './/div[@class="col span_8 push_1 position"]')
                    with open(Spis_users, 'a', encoding='cp1251') as sp_users:
                        print(gis_i_roli, ' | ', roli[j].text, sep='', file=sp_users)
                        sp_users.close()
                    j += 1

                ssilka_for_vozvrata = wait.until(
                    EC.visibility_of_element_located(
                        (By.XPATH, '//div[@class="col span_12 push_1 back"]/a[@class="link-back ng-star-inserted"]'))
                ).click()

                element = wait.until(
                    EC.visibility_of_element_located((By.XPATH, '//label[@class="input-label"]'))
                )
                time.sleep(3)

                Page_100_zapisei_N2()
                time.sleep(3)

                if (N_Page > 1) and (i < (len(elements) - 1)):
                    Kol_click = (N_Page - 1)
                    Page_navigation(Kol_click)

                elements = browser.find_elements(By.XPATH, '//li[@class="item row ng-star-inserted"]')

            except Exception:
                with open(FILENAME, 'a', encoding='cp1251') as f:
                    print('При обработке пользователя', fio.text, 'возникла ошибка', file=f)
                    print('Класс ошибки =>', sys.exc_info()[0], file=f)
                    print('Наименование ошибки =>', sys.exc_info()[1], file=f)
                    print('№ строки с ошибкой в исходном коде Python =>', sys.exc_info()[2].tb_lineno, file=f)
                    print('', file=f)
                    f.close()
            finally:
                i += 1
                with open(Spis_users, 'a', encoding='cp1251') as sp_users:
                    print('=' * 70, file=sp_users)
                    sp_users.close()

        if found_elem_next == False:
            vihod = True

        try:
            if found_elem_next == True:
                element_next = wait.until(
                    EC.element_to_be_clickable((By.XPATH, '//div[@class="pagination-next"]'))
                )
                found_elem_next = True
                N_Page = (N_Page + 1)
                if N_Page > 1:
                    Kol_click = (N_Page - 1)
                    Page_navigation(Kol_click)

                time.sleep(1)

                elements = browser.find_elements(By.XPATH, '//li[@class="item row ng-star-inserted"]')

        except Exception:
            with open(FILENAME, 'a', encoding='cp1251') as f:
                print('Класс ошибки =>', sys.exc_info()[0], file=f)
                print('Наименование ошибки =>', sys.exc_info()[1], file=f)
                print('№ строки с ошибкой в исходном коде Python =>', sys.exc_info()[2].tb_lineno, file=f)
                print('', file=f)
                f.close()
                found_elem_next = False
                elements = browser.find_elements(By.XPATH, '//li[@class="item row ng-star-inserted"]')

dt = datetime.datetime.now()
with open(FILENAME, 'a', encoding='cp1251') as f:
    print('Дата и время завершения работы скрипта ->', dt.strftime("%d.%m.%Y г.  время: %H:%M:%S"), file=f)
    print('', file=f)
f.close()

browser.quit()
sys.exit()