Управление файлами cookie с помощью Python Selenium WebDriver: методы сохранения и загрузки

Чтобы сохранять и загружать файлы cookie с помощью Python с Selenium WebDriver, вы можете использовать следующие методы:

  1. Сохранение файлов cookie.
    Чтобы сохранить файлы cookie, вы можете использовать метод get_cookies(), чтобы получить файлы cookie из текущего сеанса и сохранить их в файле или любом другом месте. желаемый объем памяти.

    from selenium import webdriver
    # Initialize the WebDriver
    driver = webdriver.Firefox()
    # Navigate to a website
    driver.get("https://www.example.com")
    # Get the cookies
    cookies = driver.get_cookies()
    # Save the cookies to a file
    with open("cookies.txt", "w") as file:
       file.write(str(cookies))
    # Close the WebDriver
    driver.quit()
  2. Загрузка файлов cookie.
    Чтобы загрузить файлы cookie, вы можете прочитать сохраненные файлы cookie из файла и добавить их в WebDriver с помощью метода add_cookie().

    from selenium import webdriver
    # Initialize the WebDriver
    driver = webdriver.Firefox()
    # Navigate to a website
    driver.get("https://www.example.com")
    # Load the cookies from the file
    with open("cookies.txt", "r") as file:
       cookies = eval(file.read())
    # Add the cookies to the WebDriver
    for cookie in cookies:
       driver.add_cookie(cookie)
    # Refresh the page to apply the loaded cookies
    driver.refresh()
    # Close the WebDriver
    driver.quit()

Эти методы позволяют сохранять файлы cookie из сеанса и загружать их позже, чтобы возобновить сеанс с сохраненным состоянием.