Задать вопрос
@Vinovat

Как устранить проблему с selenium со связкой aiogram на vps сервере?

ну коротко и сразу
использую selenium со связкой aiogram 3.17.0
ОС ubuntu 22.04
на винде все работало
пробовал также убирать --user-data-dir ничего не меняется
код бота(сильно сокращенный в оригинале все работает как надо):

bot = Bot("bot_token", default=DefaultBotProperties(parse_mode=ParseMode.HTML))
dp = Dispatcher()

user_data_dir = tempfile.mkdtemp()

options = Options()
options.add_argument("--headless")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_argument("--no-sandbox")
options.add_argument('--start-maximized')
options.add_argument(f"--user-data-dir={user_data_dir}")
options.add_argument("--incognito")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-gpu")
async def handle_task(callback: CallbackQuery, username: str, password: str, action: str):
    await callback.message.answer(f"Выполняю, ожидайте")
    await run_selenium_task(username, password, action, callback)

async def run_selenium_task(username: str, password: str, action: str, callback: CallbackQuery):
    ob = Screenshot.Screenshot()
    service = Service(r"/root/elschool/chromedriver/chromedriver",log_path='chromedriver.log')
    browser = webdriver.Chrome(service=service)

    try:
        browser.set_window_size(1920, 1080)
        browser.get("https://elschool.ru/logon/index")

        WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.ID, "login"))
        )

        entry_wrapper_btn = browser.find_element(By.CSS_SELECTOR, "div.btn.btn-light.col.entry-wrapper-btn")
        browser.execute_script("arguments[0].click();", entry_wrapper_btn)

        find_login = browser.find_element(By.ID, "login")
        browser.execute_script("arguments[0].scrollIntoView();", find_login)
        time.sleep(1)
        find_login.send_keys(username)
        find_password = browser.find_element(By.ID, "password")
        find_password.send_keys(password)
        find_password.send_keys(Keys.RETURN)

        if action == "dz":
            
            
            
            
            browser.execute_script("arguments[0].setAttribute('style', 'position: absolute; top: 0px;')", topnav4)
        elif action == "dz2":
            browser.get("https://elschool.ru/users/diaries")
            nextweek = browser.find_element(By.CSS_SELECTOR, "i.fa.fa-chevron-right")
            browser.execute_script("arguments[0].click();", nextweek)
            
        elif action == "tabel":
            browser.get("https://elschool.ru/users/diaries")
            tab_link = browser.find_element(By.LINK_TEXT, "Табель")
            tab_link.click()
            

        blackmode = browser.find_element(By.CSS_SELECTOR, "i.fa.fa-moon-o")
        browser.execute_script("arguments[0].click();", blackmode)

        img = ob.full_screenshot(browser, save_path='.', image_name='screenshot.png')
        screenshot_image = Image.open('screenshot.png')


        table = browser.find_element(By.CSS_SELECTOR, "main.container-fluid")
        location = table.location
        size = table.size
        left = location['x']
        top = location['y']
        right = left + size['width']
        bottom = top + size['height']
        table_image = screenshot_image.crop((left, top, right, bottom))
        table_image.save('table_screenshot.png')

        await callback.message.answer_photo(photo=FSInputFile('table_screenshot.png'), caption='Ваши данные')


@dp.message(Command('start'))
async def start(message: types.Message):
    catalog = InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text='Табель', callback_data='tabel')],
        [InlineKeyboardButton(text='Итоговые', callback_data='itog')],
        [InlineKeyboardButton(text='Д/З', callback_data='dz'), InlineKeyboardButton(text='След. Д/З', callback_data='dz2')],
        [InlineKeyboardButton(text='Открытый исходный код', url='https://github.com/Afteroid/elschool/')]])
    await message.answer("Выберите что хотите узнать\n\n(если бот не отвечает долгое время значит вы стоите в очереди, в скорем времени бот ответит вам)", reply_markup=catalog)

@dp.callback_query(F.data.in_({"dz", "dz2", "itog", "tabel"}))
async def handle_callback(callback: CallbackQuery):
    async with aiosqlite.connect('users.db') as db:
        async with db.execute('SELECT username, password FROM users WHERE tg_id = ?',
                              (callback.from_user.id,)) as cursor:
            user = await cursor.fetchone()
            if user:
                username, password = user
                action = callback.data
                asyncio.create_task(handle_task(callback, username, password, action))
            else:
                await callback.message.reply("Пользователь не найден.")

сам код ошибки при нажатии одну из кнопок:
Task exception was never retrieved
future: <Task finished name='Task-16' coro=<handle_task() done, defined at /root/elschool/main.py:49> exception=SessionNotCreatedException()>
Traceback (most recent call last):
  File "/root/elschool/main.py", line 51, in handle_task
    await run_selenium_task(username, password, action, callback)
  File "/root/elschool/main.py", line 56, in run_selenium_task
    browser = webdriver.Chrome(service=service)
  File "/usr/local/lib/python3.10/dist-packages/selenium/webdriver/chrome/webdriver.py", line 45, in __init__
    super().__init__(
  File "/usr/local/lib/python3.10/dist-packages/selenium/webdriver/chromium/webdriver.py", line 66, in __init__
    super().__init__(command_executor=executor, options=options)
  File "/usr/local/lib/python3.10/dist-packages/selenium/webdriver/remote/webdriver.py", line 250, in __init__
    self.start_session(capabilities)
  File "/usr/local/lib/python3.10/dist-packages/selenium/webdriver/remote/webdriver.py", line 342, in start_session
    response = self.execute(Command.NEW_SESSION, caps)["value"]
  File "/usr/local/lib/python3.10/dist-packages/selenium/webdriver/remote/webdriver.py", line 429, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python3.10/dist-packages/selenium/webdriver/remote/errorhandler.py", line 232, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: probably user data directory is already in use, please specify
a unique value for --user-data-dir argument, or don't use --user-data-dir
Stacktrace:
#0 0x55fa1533c53a <unknown>
#1 0x55fa14e37f00 <unknown>
#2 0x55fa14e6ec53 <unknown>
#3 0x55fa14e6b4b6 <unknown>
#4 0x55fa14eb87b6 <unknown>
#5 0x55fa14eb7e06 <unknown>
#6 0x55fa14eac343 <unknown>
#7 0x55fa14e7978a <unknown>
#8 0x55fa14e7a9de <unknown>
#9 0x55fa153062cb <unknown>
#10 0x55fa1530a242 <unknown>
#11 0x55fa152f37ac <unknown>
#12 0x55fa1530adf7 <unknown>
#13 0x55fa152d7b2f <unknown>
#14 0x55fa1532b1a8 <unknown>
#15 0x55fa1532b370 <unknown>
#16 0x55fa1533b3b6 <unknown>
#17 0x7fc3189cbac3 <unknown>
  • Вопрос задан
  • 32 просмотра
Подписаться 1 Простой 2 комментария
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы