web页面中cookie是一个很重要的信息,那么selenium也自然有方法能够操作cookie,废话不多说,搞起来~
用法 几种操作cookie的方法
1fuck_test.get_cookies() #获取cookie
2fuck_test.add_cookie(cookie_dict={'name','phyger'})#增加cookie
3fuck_test.delete_cookie('name')#删除指定cookie
4fuck_test.delete_all_cookies()#删除所有cookie
例子 实现cookie的获取,增加,打印和删除
页面
1
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>test</title>
6 <script src=”http://libs.baidu.com/jquery/2.1.1/jquery.min.js”></script>
7</head>
8<body>
9<h1>fuck_test</h1>
10<div>
11 <input type="checkbox" id="china"><label for="china">China</label><br>
12 <input type="checkbox" id="Canada"><label for="Canada">Canada</label><br>
13 <input type="checkbox" id="Japan"><label for="Japan">Japan</label><br>
14 <input type="checkbox" id="US"><label for="US">US</label><br>
15 <iframe id="fuck" src="https://www.baidu.com" width="1000" height="500" frameborder="1/0" name="test" scrolling="auto">
16</iframe>
17</div>
18</body>
19</html>
增加并打印cookie
1#encoding=utf-8
2from selenium import webdriver
3import time
4fuck_test=webdriver.Chrome()
5fuck_test.maximize_window()
6fuck_test.get("https://www.baidu.com")
7time.sleep(2)
8cookie=fuck_test.get_cookies()
9print cookie
10#增加一个cookie
11fuck_test.add_cookie({'name':'sex','value':'man'})
12#获取并打印cookie
13cookie=fuck_test.get_cookies()
14print cookie
15time.sleep(2)
16fuck_test.quit()
删除增加的cookie
1#encoding=utf-8
2from selenium import webdriver
3import time
4fuck_test=webdriver.Chrome()
5fuck_test.maximize_window()
6fuck_test.get("https://www.baidu.com")
7time.sleep(2)
8cookie1=fuck_test.get_cookies()
9print cookie1
10#增加一个cookie
11fuck_test.add_cookie({'name':'sex','value':'man'})
12cookie2=fuck_test.get_cookies()
13print cookie2
14#删除增加的cookie
15fuck_test.delete_cookie('sex')
16cookie3=fuck_test.get_cookies()
17print cookie3
18time.sleep(2)
19fuck_test.quit()
删除所有的cookie
1#encoding=utf-8
2from selenium import webdriver
3import time
4fuck_test=webdriver.Chrome()
5fuck_test.maximize_window()
6fuck_test.get("https://www.baidu.com")
7time.sleep(2)
8cookie1=fuck_test.get_cookies()
9print cookie1
10#增加一个cookie
11fuck_test.add_cookie({'name':'sex','value':'man'})
12cookie2=fuck_test.get_cookies()
13print cookie2
14#删除增加的cookie
15fuck_test.delete_cookie('sex')
16cookie3=fuck_test.get_cookies()
17print cookie3
18fuck_test.delete_all_cookies()
19cookie4=fuck_test.get_cookies()
20print cookie4
21time.sleep(2)
22fuck_test.quit()
小结
cookie是web服务器为了识别用户的身份而保留在本地终端上数据,也称为浏览器缓存,session是用来标示用户状态的。
ok,今天就到这,想了解更多请关注搞测试,祝你看的愉快~兄dei~如果你觉得还行大家一起学习,共同进步~