如何使用 nodriver (Python) 保存会话?

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

我想了解如何使用 nodriver 保存和加载会话(cookies)。我找到了一个例子(https://stabler.tech/blog/nodriver-a-new-webscraping-tool),但代码似乎已经过时了。

我发现了一些旧的 github 事件,开发人员对此说了一些话并发布了一些代码。 (https://github.com/ultrafunkamsterdam/unDetected-chromedriver/issues/1817 // https://github.com/ultrafunkamsterdam/unDetected-chromedriver/issues/1816)

我尝试了几个小时不同的东西,即使使用 Gemini 和 ChatGPT,但我做不到。我对 Python 还很陌生。有人可以帮助我吗?

这是可执行的示例代码:

import asyncio
import nodriver as uc

user = "User"
password = "passwort"


async def type_text(element, text):
    for char in text:
        await element.send_keys(char)


async def main():
    browser = None
    try:
        browser = await uc.start()
        page = await browser.get('https://html-php.de/php/zb_php_f/index.php')

        email_field = await page.select("input[name=a_nick]")
        password_field = await page.select("input[name=a_pass]")
        login_task = None

        if email_field and password_field:
            await type_text(email_field, user)
            await type_text(password_field, password)

            login_button = await page.select("input[type=submit]")
            if login_button:
                login_task = asyncio.create_task(login_button.click())

        if login_task:
            await login_task

    except Exception as e:
        print(f"Error during login: {e}")
    finally:
        if browser:
            # Wait for 10 seconds before closing
            await asyncio.sleep(10)
            await browser.stop()


if __name__ == '__main__':
    uc.loop().run_until_complete(main())

我想实现,当我第二次启动它时,它已经登录了。(所以应该抛出异常)。

(我无法使用“nodriver”标签,所以我使用了“unDetected-chromedriver”,它的前身)

python undetected-chromedriver
1个回答
0
投票

好吧,很幸运,我终于找到了一个文档(https://ultrafunkamsterdam.github.io/nodriver/)...自述文件中没有提到它,因此我可以帮助自己:)

这是代码,如果其他人有兴趣的话^^

import nodriver as uc
import json

USER = "User"
PASSWORD = "passwort"
COOKIE_FILE_NAME = ".session.dat"


async def type_text(element, text):
    for char in text:
        await element.send_keys(char)


async def login_with_credentials(page):
    email_field = await page.select("input[name=a_nick]")
    password_field = await page.select("input[name=a_pass]")

    if not email_field or not password_field:
        return False

    print("Logging in with credentials...")
    await type_text(email_field, USER)
    await type_text(password_field, PASSWORD)

    login_button = await page.select("input[type=submit]")
    if login_button:
        await login_button.click()
        return True

    return False


async def load_cookies(browser, page):
    try:
        await browser.cookies.load(COOKIE_FILE_NAME)
        await page.reload()
        print("Cookies loaded.")
        return True
    except (json.JSONDecodeError, ValueError) as e:
        print(f"Failed to load cookies: {e}")
    except FileNotFoundError:
        print("Cookie file does not exist.")

    return False


async def save_cookies(browser):
    try:
        await browser.cookies.save(COOKIE_FILE_NAME)
        print("Cookies saved.")
    except Exception as e:
        print(f"Failed to save cookies: {e}")


async def main():
    try:
        browser = await uc.start()
        page = await browser.get('https://html-php.de/php/zb_php_f/index.php')

        if not await load_cookies(browser, page):
            if not await login_with_credentials(page):
                print("Login failed.")
                return False

            await save_cookies(browser)
            print("Logged in with credentials and cookies saved.")
        else:
            print("Logged in with cookies.")

        await page.sleep(5)
        # browser.stop()
    except Exception as e:
        print(f"Error during login: {e}")

if __name__ == '__main__':
    uc.loop().run_until_complete(main())
© www.soinside.com 2019 - 2024. All rights reserved.