如何使用 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.com/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()

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

更新于:2021-02-01

1K+ 查看次数

开启您的 职业生涯

完成课程并获得认证

开始
广告