如何使用 Python 和 Selenium 操作 Cookie?


我們可以透過 Selenium 提供的多種方法來操作 Cookie,這些方法可以控制瀏覽器或其會話。我們可以輕鬆地新增或刪除 Cookie。Cookie 的實現對於確保網站的正確身份驗證至關重要。

操作 Cookie 的方法如下所示:

  • add_cookie(args)

    此方法將 Cookie 新增到當前會話中。引數包含我們要新增的 Cookie 的名稱。

語法

driver.add_cookie({'id' : 'val' : 'session'})
  • get_cookie(args)

    此方法獲取特定名稱的 Cookie。引數包含我們要檢索的 Cookie 的名稱。

語法

driver.get_cookie("name")
  • delete_cookie(args)

    此方法刪除特定名稱的 Cookie。引數包含我們要刪除的 Cookie 的名稱。

語法

driver.delete_cookie("session")
  • delete_all_cookies()

    此方法刪除當前會話中的所有 Cookie。它沒有引數。

語法

driver.delete_all_cookies()
  • get_cookies()

    此方法以字典的形式返回當前會話中的所有 Cookie。

語法

driver.get_cookies()

示例

Cookie 新增和刪除的程式碼實現。

from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://tutorialspoint.tw/selenium/selenium_automation_practice.htm")
#to refresh the browser
driver.refresh()
#to add cookies of particular names
driver.add_cookie({'id' : 'val': 'session'})
#to get a specific cookie
print(driver.get_cookie("id"))
#to get all cookies of the session
print(driver.get_cookies())
#to delete a particular cookie
driver.delete_cookie("val")
#to delete all cookies in present session
driver.delete_all_cookies()

更新於: 2020-07-29

693 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告