如何使用 Python 在 Selenium Webdriver 中為特定域設定 cookie?


我們可以在 Selenium Webdriver 中使用 Python 為特定域設定 cookie。Cookie 用於儲存瀏覽器傳送的資訊。它採用鍵值成對的形式,就像伺服器傳送給瀏覽器的訊息一樣。

對於 cookie 的新增,使用了**add_cookie**方法。鍵和值作為引數傳遞給該方法。要獲取所有 cookie,請使用get_cookies方法。要獲取特定 cookie,請使用get_cookie方法。

要刪除 cookie,請使用**delete_all_cookies**方法。

語法

driver.add_cookie({"Automation": "QA"});
c= driver.get_cookies();
driver.get_cookie({"Automation");
driver.delete_all_cookies();

示例

from selenium import webdriver
#set geckodriver.exe path
driver = webdriver.Firefox(executable_path="C:\geckodriver.exe")
driver.maximize_window()
#launch URL
driver.get("https://tutorialspoint.tw/index.htm")
#add cookie
c = {'name' : "Automation", 'value' : 'QA'}
driver.add_cookie(c);
#count total cookies
print(len(driver.get_cookies()))
#obtain cookie with name
print(driver.get_cookie("Automation"))
#delete cookies
driver.delete_all_cookies();
#check cookies after delete
d = driver.get_cookies()
print("Cookie count after all deletion")
print(len(d))
#close browser
driver.quit()

輸出

更新於:2021-02-01

1K+ 檢視次數

開啟您的 職業生涯

完成課程並獲得認證

開始
廣告