1. import json
  2. import os
  3. def load_cookies(filepath):
  4. """Loads cookies from a JSON file.
  5. Args:
  6. filepath (str): The path to the JSON file containing cookies.
  7. Returns:
  8. dict: A dictionary of cookies, or an empty dictionary if the file
  9. doesn't exist or is invalid.
  10. """
  11. try:
  12. with open(filepath, 'r') as f:
  13. cookies = json.load(f)
  14. return cookies
  15. except FileNotFoundError:
  16. print(f"Cookie file not found: {filepath}")
  17. return {}
  18. except json.JSONDecodeError:
  19. print(f"Invalid JSON format in cookie file: {filepath}")
  20. return {}
  21. def create_dummy_cookies(filepath):
  22. """Creates a dummy cookie file for testing.
  23. Args:
  24. filepath (str): The path to the file to create.
  25. """
  26. cookies = {
  27. "example_site": {"session_id": "1234567890", "user_id": "user123"},
  28. "another_site": {"auth_token": "abcdef123456"}
  29. }
  30. with open(filepath, 'w') as f:
  31. json.dump(cookies, f, indent=4)
  32. if __name__ == '__main__':
  33. cookie_file = "cookies.json" # Define the cookie file path
  34. # Create a dummy cookie file if it doesn't exist
  35. if not os.path.exists(cookie_file):
  36. create_dummy_cookies(cookie_file)
  37. cookies = load_cookies(cookie_file)
  38. print(cookies)

Add your comment