前言
虽然cookie相关操作在平常ui自动化中用得少,偶尔也会用到,比如登录有图形验证码,可以通过绕过验证码方式,添加cookie方法登录。
登录后换账号登录时候,也可作为后置条件去删除cookie然后登录下个账号
一、获取cookies:get_cookies()
1.获取cookies方法直接用:get_cookies()
2.先启动浏览器,获取cookies,打印出来发现是空:[]
3.打开博客首页后,重新获取cookies,打印出来,就有值了
# coding:utf-8 from selenium import webdriver import time driver=webdriver.Chrome() print("打开浏览器后,查看cookie结果:{}".format(driver.get_cookies())) driver.get("http://www.cnblogs.com/canglongdao/") print("访问canglongdao博客园,查看cookie结果:{}".format(driver.get_cookies()))
运行结果:
打开浏览器后,查看cookie结果:[] 访问canglongdao博客园,查看cookie结果:[{'domain': '.cnblogs.com', 'expiry': 1599099565, 'httpOnly': False, 'name': '_gid', 'path': '/', 'secure': False, 'value': 'GA1.2.506249297.1599013166'}, {'domain': '.cnblogs.com', 'expiry': 1662085165, 'httpOnly': False, 'name': '_ga', 'path': '/', 'secure': False, 'value': 'GA1.2.1600623487.1599013166'}]
二、登录后的cookies
1.先登录博客园(需要改成自己的账号和密码)
2.重新获取cookies,发现跟之前获取的不一样了
3.主要是找到这一个cookie,发现它的name和value发生了变化,这就是未登录和已登录的区别了
{'domain': '.cnblogs.com', 'expiry': 1600309421, 'httpOnly': True, 'name': '.Cnblogs.AspNetCore.Cookies', 'path': '/', 'secure': False, 'value': 'CfDJ8K5MrGQfPjpFvRyctF-QEQdlqzhqG6PZtQKQrvpGfVSWEsJhfqznqKwPW7PWGQMy3IhudpppvC4A0Im_RwQofGzos_48A6w'}
注意:登录有时需要拖动滑块拼图,这里可以添加等待时间time.sleep(n),然后手动拼图
# coding:utf-8 from selenium import webdriver import time driver=webdriver.Chrome() print("打开浏览器后,查看cookie结果:{}".format(driver.get_cookies())) driver.get("http://www.cnblogs.com/canglongdao/") print("访问canglongdao博客园,查看cookie结果:{}".format(driver.get_cookies())) driver.get("https://account.cnblogs.com/signin?returnUrl=https:%2F%2Fwww.cnblogs.com%2F") driver.find_element_by_id("mat-input-0").send_keys("333@qq.com") driver.find_element_by_id("mat-input-1").send_keys("P@ssw0rd") driver.find_element_by_xpath("//div[@class='ng-tns-c141-2 ng-star-inserted']/button[@mat-flat-button='']").click() time.sleep(6) driver.maximize_window() print("登录博客园,查看cookie:{}".format(driver.get_cookies()))
运行结果:
"D:Program Filespython37python.exe" E:/study/selenium_study/a825.py 打开浏览器后,查看cookie结果:[] 访问canglongdao博客园,查看cookie结果:[{'domain': '.cnblogs.com', 'expiry': 1599099813, 'httpOnly': False, 'name': '_gid', 'path': '/', 'secure': False, 'value': 'GA1.2.759010773.1599013414'}, {'domain': '.cnblogs.com', 'expiry': 1662085413, 'httpOnly': False, 'name': '_ga', 'path': '/', 'secure': False, 'value': 'GA1.2.431778497.1599013414'}] 登录博客园,查看cookie:[{'domain': '.cnblogs.com', 'expiry': 1662085423, 'httpOnly': False, 'name': '__gads', 'path': '/', 'secure': False, 'value': 'ID=bf09a693c7fead68-2206974f46c3000f:T=1599013423:S=ALNI_Mbqvosrdrq3rE8h9uzctpVTVeZAyw'}, {'domain': '.cnblogs.com', 'expiry': 1600309421, 'httpOnly': True, 'name': '.CNBlogsCookie', 'path': '/', 'secure': False, 'value': '5ABD8FE57A40B86EB5095482D6627EE7D7EAD13656D017453A1DABA697DB8C69C692DF5E0C7EBC8F00EAE603DB51AC3C712038DC65ECB12E192C3EB9E3802AA769D4F36D500540A8F830BEC1A8F1A082D5047DCF'}, {'domain': '.cnblogs.com', 'expiry': 1599013481, 'httpOnly': False, 'name': '_gat', 'path': '/', 'secure': False, 'value': '1'}, {'domain': '.cnblogs.com', 'expiry': 1600309421, 'httpOnly': True, 'name': '.Cnblogs.AspNetCore.Cookies', 'path': '/', 'secure': False, 'value': 'CfDJ8K5MrGQfPjpFvRyctF-QEQdlqzhqG6PZtQKQrvpGfVSWEsJhfqznqKwPW7PWGQMy3IhudpppvC4A0Im_RwQofGzos_48A6wx5y2chNOYJIdkq4wJ60YOvvlIbQJrfaUX5GU3VZ4UitneBpy4e-ZEiRT66JWkw80quUxS9xgQhdRgTaKfdpTQ7iIoiMLuLL9NNFBi07rctOb9LjsgsQu9u9wV7bHSfnSkZjmDT49SJpSvvbQA1KsQ1NPgLPoXd3gumEdZFL7OrpTp_bATBmlfIMqrwb_Y_Ue6707qeUN2gqQacWjC4jBMlwJpRyyt74ygZ3VHaB0jn7seWwbfEJ2-sT-eBk4ylve_8wLEFaN2W0uUNgr7BKxBIglWjDzyQ-k3Ulm9WYE9-JAY8keedhjcigAHsdtnK2PxawNCIfjQEASgUUELpfExIdQPybR6wg0TD_GIaXGR0Lm_fErU9KtdbxO4reSscwhkN5PV8tPMGSgUuuCQdNjXDb--73vtXYytHB1xXbx12sd4hJ-PvfTrhp2EAh0LblvBCQ_e2BvPopwjE2gzQZg'}, {'domain': '.cnblogs.com', 'expiry': 1599099821, 'httpOnly': False, 'name': '_gid', 'path': '/', 'secure': False, 'value': 'GA1.2.759010773.1599013414'}, {'domain': '.cnblogs.com', 'expiry': 1662085421, 'httpOnly': False, 'name': '_ga', 'path': '/', 'secure': False, 'value': 'GA1.2.431778497.1599013414'}] Process finished with exit code 0
三、获取指定name的cookie:driver.get_cookie(name)
1.获取cookies发现里面有多个cookie,有时候我们只需要其中的一个,把重要的提出来,比如登录的cookie
2.这里用get_cookie(name),指定对应的cookie的name值就行了,比如博客园的:.Cnblogs.AspNetCore.Cookies
# #获取指定name的cookie print(driver.get_cookie(name=".Cnblogs.AspNetCore.Cookies"))
四、清除指定cookie: delete_cookie()
1.为了进一步验证上一步获取到的就是登录的cookie,可以删除它看看页面什么变化
2.删除这个cookie后刷新页面,发现刚才的登录已经失效了,变成未登录状态了
# #清除指定name的cookie driver.delete_cookie(name=".Cnblogs.AspNetCore.Cookies") print("删除部分cookie,查看cookies:{}".format(driver.get_cookies())) driver.refresh()
五、清除所有cookies: delete_all_cookies()
1.清除所有cookies后登录状态也失效了,cookies为空[]
# #清除所有cookies driver.delete_all_cookies()
参考代码:
# coding:utf-8 from selenium import webdriver import time driver=webdriver.Chrome() print("打开浏览器后,查看cookie结果:{}".format(driver.get_cookies())) driver.get("http://www.cnblogs.com/canglongdao/") print("访问canglongdao博客园,查看cookie结果:{}".format(driver.get_cookies())) driver.get("https://account.cnblogs.com/signin?returnUrl=https:%2F%2Fwww.cnblogs.com%2F") driver.find_element_by_id("mat-input-0").send_keys("333@qq.com") driver.find_element_by_id("mat-input-1").send_keys("P@ssw0rd") driver.find_element_by_xpath("//div[@class='ng-tns-c141-2 ng-star-inserted']/button[@mat-flat-button='']").click() time.sleep(6) driver.maximize_window() print("登录博客园,查看cookie:{}".format(driver.get_cookies())) #获取指定name的cookie # print(driver.get_cookie(name=".CNBlogsCookie")) print(driver.get_cookie(name=".Cnblogs.AspNetCore.Cookies")) #刷新页面 driver.refresh() time.sleep(2) #清除指定name的cookie # driver.delete_cookie(name=".CNBlogsCookie") driver.delete_cookie(name=".Cnblogs.AspNetCore.Cookies") print("删除部分cookie,查看cookies:{}".format(driver.get_cookies())) driver.refresh() time.sleep(2) #清除所有cookies driver.delete_all_cookies() print("删除所有cookies,查看cookies:{}".format(driver.get_cookies()))
运行结果:
打开浏览器后,查看cookie结果:[] 访问canglongdao博客园,查看cookie结果:[{'domain': '.cnblogs.com', 'expiry': 1599101956, 'httpOnly': False, 'name': '_gid', 'path': '/', 'secure': False, 'value': 'GA1.2.1722891321.1599015556'}, {'domain': '.cnblogs.com', 'expiry': 1662087556, 'httpOnly': False, 'name': '_ga', 'path': '/', 'secure': False, 'value': 'GA1.2.276388436.1599015556'}] 登录博客园,查看cookie:[{'domain': '.cnblogs.com', 'expiry': 1662087568, 'httpOnly': False, 'name': '__gads', 'path': '/', 'secure': False, 'value': 'ID=756cab89ab760b32-228614e13dc300d7:T=1599015568:S=ALNI_MZu9eDQTT5rPH94eVRz6ITqYXBl2w'}, {'domain': '.cnblogs.com', 'expiry': 1600311566, 'httpOnly': True, 'name': '.CNBlogsCookie', 'path': '/', 'secure': False, 'value': '57816AE9359FC0EBB0E29CFC6DB54D1C9755DC24DFD280F53FB69E4373FEE5E100F048F349CBA6F525E3BCCC929470368F79FC580A93BE6C5F1704D94D25BB81E14D66D014673718D1525904BAC926F65276B44E'}, {'domain': '.cnblogs.com', 'expiry': 1599015626, 'httpOnly': False, 'name': '_gat', 'path': '/', 'secure': False, 'value': '1'}, {'domain': '.cnblogs.com', 'expiry': 1600311566, 'httpOnly': True, 'name': '.Cnblogs.AspNetCore.Cookies', 'path': '/', 'secure': False, 'value': 'CfDJ8K5MrGQfPjpFvRyctF-QEQeI02AzdFdRMxR-3IUWETGf86Kd5SwmYUqyXkOpP6ZgviFOryIP0081_2UrxxAb8ElIgUTuB9R5cMyuifY1KoZu8Rh7ox7rHxyUdnaLJZNmQkqt04TXwSiJQann36kQ2t_MrWFytPzs7groCHrJX4qkkKcvLSvjicxSsTuQzy1qo3UpiVr5EnF4pBBcYWyPASJ-oXetn-8DbnTeuW226Fbx2qoK-jsl177eoB8GAA1FhZzBcV9BZny-yqJZkW99TH4JTMqhyuQGM1e_dx8JEMsTCAkUvPRnLpeRO3OtfP8GaEgFUQHlOo7I2l3SzEI5HOZI9v_xHZheUm8Ti48TI4Z5W2jcmxGBhBzdc74BIQM4srrosgoTm6JREqERPVZ07hMtxTxY1n1fljPSir18Tn-wfk8X66JxzW1couqtbSUwB2hJZxWJBxNqteHSd4f-dM8gmJHqXZPphiatByTB2gQSptEDpwokTcK29TRd-jGkW3LgdREkjvyyMOVfnIRJZu7hcj2cVMFLbq0vAltWdVoJSD-9vzzuWRDxq-LAYooO7A'}, {'domain': '.cnblogs.com', 'expiry': 1599101966, 'httpOnly': False, 'name': '_gid', 'path': '/', 'secure': False, 'value': 'GA1.2.1722891321.1599015556'}, {'domain': '.cnblogs.com', 'expiry': 1662087566, 'httpOnly': False, 'name': '_ga', 'path': '/', 'secure': False, 'value': 'GA1.2.276388436.1599015556'}] {'domain': '.cnblogs.com', 'expiry': 1600311566, 'httpOnly': True, 'name': '.Cnblogs.AspNetCore.Cookies', 'path': '/', 'secure': False, 'value': 'CfDJ8K5MrGQfPjpFvRyctF-QEQeI02AzdFdRMxR-3IUWETGf86Kd5SwmYUqyXkOpP6ZgviFOryIP0081_2UrxxAb8ElIgUTuB9R5cMyuifY1KoZu8Rh7ox7rHxyUdnaLJZNmQkqt04TXwSiJQann36kQ2t_MrWFytPzs7groCHrJX4qkkKcvLSvjicxSsTuQzy1qo3UpiVr5EnF4pBBcYWyPASJ-oXetn-8DbnTeuW226Fbx2qoK-jsl177eoB8GAA1FhZzBcV9BZny-yqJZkW99TH4JTMqhyuQGM1e_dx8JEMsTCAkUvPRnLpeRO3OtfP8GaEgFUQHlOo7I2l3SzEI5HOZI9v_xHZheUm8Ti48TI4Z5W2jcmxGBhBzdc74BIQM4srrosgoTm6JREqERPVZ07hMtxTxY1n1fljPSir18Tn-wfk8X66JxzW1couqtbSUwB2hJZxWJBxNqteHSd4f-dM8gmJHqXZPphiatByTB2gQSptEDpwokTcK29TRd-jGkW3LgdREkjvyyMOVfnIRJZu7hcj2cVMFLbq0vAltWdVoJSD-9vzzuWRDxq-LAYooO7A'} 删除部分cookie,查看cookies:[{'domain': '.cnblogs.com', 'expiry': 1662087568, 'httpOnly': False, 'name': '__gads', 'path': '/', 'secure': False, 'value': 'ID=756cab89ab760b32:T=1599015568:S=ALNI_MY1zMc4_iZ_nPtjJpVUvdQGA2BjQg'}, {'domain': '.cnblogs.com', 'expiry': 1599015626, 'httpOnly': False, 'name': '_gat', 'path': '/', 'secure': False, 'value': '1'}, {'domain': '.cnblogs.com', 'expiry': 1600311566, 'httpOnly': True, 'name': '.CNBlogsCookie', 'path': '/', 'secure': False, 'value': '57816AE9359FC0EBB0E29CFC6DB54D1C9755DC24DFD280F53FB69E4373FEE5E100F048F349CBA6F525E3BCCC929470368F79FC580A93BE6C5F1704D94D25BB81E14D66D014673718D1525904BAC926F65276B44E'}, {'domain': '.cnblogs.com', 'expiry': 1599101967, 'httpOnly': False, 'name': '_gid', 'path': '/', 'secure': False, 'value': 'GA1.2.1722891321.1599015556'}, {'domain': '.cnblogs.com', 'expiry': 1662087567, 'httpOnly': False, 'name': '_ga', 'path': '/', 'secure': False, 'value': 'GA1.2.276388436.1599015556'}] 删除所有cookies,查看cookies:[]
六、cookie操作的几个方法
1.get_cookies():获取所有cookies
2.driver.get_cookie(name):获取指定name的cookie
3.清除指定cookie:delete_cookie()
4.delete_all_cookies():清除所有cookies
5.add_cookie(cookie_dict):添加cookie的值