Advertisement
sourav8256

Untitled

Aug 26th, 2023
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. from selenium import webdriver
  2. import pickle
  3.  
  4. class CookieManager:
  5. def __init__(self, driver=None):
  6. self.driver = driver
  7.  
  8. def save_cookies(self, filename):
  9. if self.driver is None:
  10. raise ValueError("Driver instance not provided.")
  11.  
  12. cookies = self.driver.get_cookies()
  13. with open(filename, 'wb') as f:
  14. pickle.dump(cookies, f)
  15.  
  16. def load_cookies(self, filename):
  17. if self.driver is None:
  18. raise ValueError("Driver instance not provided.")
  19.  
  20. with open(filename, 'rb') as f:
  21. cookies = pickle.load(f)
  22. for cookie in cookies:
  23. self.driver.add_cookie(cookie)
  24.  
  25. # Example usage
  26. if __name__ == "__main__":
  27. # Initialize a WebDriver instance
  28. driver = webdriver.Chrome() # You can use any browser driver you prefer
  29.  
  30. # Create a CookieManager instance
  31. cookie_manager = CookieManager(driver)
  32.  
  33. # Navigate to a website to get some cookies
  34. driver.get("https://example.com")
  35. # Perform some actions to get cookies if needed
  36.  
  37. # Save cookies to a file
  38. cookie_manager.save_cookies("cookies.pkl")
  39.  
  40. # Close the current browser session
  41. driver.quit()
  42.  
  43. # Reinitialize WebDriver instance
  44. driver = webdriver.Chrome()
  45.  
  46. # Create a new CookieManager instance
  47. cookie_manager = CookieManager(driver)
  48.  
  49. # Load cookies from the file
  50. cookie_manager.load_cookies("cookies.pkl")
  51.  
  52. # Navigate to a page that requires cookies
  53. driver.get("https://example.com/some-protected-page")
  54.  
  55. # Now the browser should have the necessary cookies loaded
  56.  
  57. # Close the browser session
  58. driver.quit()
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement