Selenium with Python 007 - Cookie处理

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Selenium with Python 007 - Cookie处理相关的知识,希望对你有一定的参考价值。

Webdriver 读取、添加、删除cookie信息基本用法

  • 获得Cookie信息:driver.get_cookies()
  • 添加Cookie信息:driver.add_cookie(cookie_dict)
  • 删除特定Cookie:delete_cookie(name)
  • 删除所有Cookie:delete_all_cookies()

 

实例演示WebDriver Cookie操作

#!/usr/bin/env python 
# -*- coding: utf-8 -*-

from selenium import webdriver

driver = webdriver.Chrome()

driver.get("http://www.baidu.com")

# 获取所有Cookie
cookies = driver.get_cookies()
print("打开百度首页后获取所有Cookie:%s" % cookies)

# 删除所有Cookie值
driver.delete_all_cookies()
print("删除所有Cookie后获取所有Cookie:%s" % driver.get_cookies())

# 添加Cookie
driver.add_cookie({name: user, value: ptqa})
driver.add_cookie({name: from, value: 4399})
print("添加Cookie后,获取所有Cookie:%s " % driver.get_cookies())

# 获取特定Cookie
user = driver.get_cookie("user")
print("添加Cookie后,获取对应特定Cookie对象:%s " % user)
if user:
    print("添加Cookie后,获取对应特定Cookie的键值:%s->%s " % (user["name"], user["value"]))

# 删除特定Cookie
driver.delete_cookie("user")
print("删除特定Cookie user后,查看所有Cookie:%s" % driver.get_cookies())

driver.close()

运行输出结果如

打开百度首页后获取所有Cookie:[{secure: False, name: H_PS_PSSID, domain: .baidu.com, path: /, httpOnly: False, value: 1453_21085_23384_20930}, {expiry: 3652321614.105473, secure: False, name: BAIDUID, domain: .baidu.com, path: /, httpOnly: False, value: D99013DD2F470724CC4CDDE361CD7606:FG=1}, {expiry: 3652321614.105604, secure: False, name: PSTM, domain: .baidu.com, path: /, httpOnly: False, value: 1504837945}, {expiry: 3652321614.10557, secure: False, name: BIDUPSID, domain: .baidu.com, path: /, httpOnly: False, value: D99013DD2F470724CC4CDDE361CD7606}, {expiry: 1505701967, secure: False, name: BD_UPN, domain: www.baidu.com, path: /, httpOnly: False, value: 12314353}, {expiry: 1504837968.105635, secure: False, name: BD_LAST_QID, domain: www.baidu.com, path: /, httpOnly: False, value: 10497571297502961037}, {secure: False, name: BD_HOME, domain: www.baidu.com, path: /, httpOnly: False, value: 0}]
删除所有Cookie后获取所有Cookie:[]
添加Cookie后,获取所有Cookie:[{expiry: 2135557968, secure: False, name: user, domain: www.baidu.com, path: /, httpOnly: False, value: ptqa}, {expiry: 2135557968, secure: False, name: from, domain: www.baidu.com, path: /, httpOnly: False, value: 4399}] 
添加Cookie后,获取对应特定Cookie对象:{expiry: 2135557968, secure: False, name: user, domain: www.baidu.com, path: /, httpOnly: False, value: ptqa} 
添加Cookie后,获取对应特定Cookie的键值:user->ptqa 
删除特定Cookie user后,查看所有Cookie:[{expiry: 2135557968, secure: False, name: from, domain: www.baidu.com, path: /, httpOnly: False, value: 4399}]

 

以上是关于Selenium with Python 007 - Cookie处理的主要内容,如果未能解决你的问题,请参考以下文章

Selenium with Python中文翻译文档

[Selenium+Java] How to Use Selenium with Python: Complete Tutorial

Selenium with Python 001 - 安装篇

Selenium with Python 003 - 页面元素定位

Selenium with Python 010 - unittest 框架(又称PyUnit 框架)

Selenium with Python - Chromedriver 必须在 PATH 中