[Python] Selenium how to save and load cookies

要在 chrome 裡觀看 cookie 可以這樣做:

Read on to know how you can identify the cookies using Chrome.

Step 1: switch on Chrome’s Developer Tools

Open Chrome website and type in the URL that you want to check for the cookies. Preferably, visit the website using a private window. Next, right click on the browser window, and click on Inspect element to go to the Chrome develepor console.

Step 2: open up the “cookie” resources view

From the developer console, navigate to the Application tab. On this tab, from the storage section open the cookies resources view. This window will show all of the cookies that are installed by that webpage on the browser.

截圖:


要在 python 裡存讀/寫 cookie:

You can save the current cookies as a python object using pickle. For example:

import pickle
import selenium.webdriver 

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
pickle.dump( driver.get_cookies() , open("cookies.pkl","wb"))

and later to add them back:

import pickle
import selenium.webdriver 

driver = selenium.webdriver.Firefox()
driver.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
    driver.add_cookie(cookie)

取得 youtube cookie 範例:

youtube cookies with this:

driver = webdriver.Firefox(executable_path="driver/geckodriver.exe")
driver.get("https://www.youtube.com/")
print(driver.get_cookies())

And what I get is:

[{‘name’: ‘VISITOR_INFO1_LIVE’, ‘value’: ‘EDkAwwhbDKQ’, ‘path’: ‘/’, ‘domain’: ‘.youtube.com’, ‘expiry’: None, ‘secure’: False, ‘httpOnly’: True}]

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *