Selenium add access cookie to automatically log Selenium added automatically log cookie access

Selenium is added automatically log cookie access

 

Sometimes necessary when webDriver visit the Web site, with cookie achieve free access to the landing, the following is a simple implementation.

Log in and save cookie

'''
前面部分代码用于填写登录信息并登录
'''
# 获取cookie并通过json模块将dict转化成str
dictCookies = self.browser.get_cookies()
jsonCookies = json.dumps(dictCookies)
# 登录完成后,将cookie保存到本地文件
with open('cookies.json', 'w') as f:
    f.write(jsonCookies)

Read cookie achieve free access landing

# 初次建立连接,随后方可修改cookie
self.browser.get('http://xxxx.com')
# 删除第一次建立连接时的cookie
self.browser.delete_all_cookies()
# 读取登录时存储到本地的cookie
with open('cookies.json', 'r', encoding='utf-8') as f:
    listCookies = json.loads(f.read())
for cookie in listCookies:
    self.browser.add_cookie({
        'domain': '.xxxx.com',  # 此处xxx.com前,需要带点
        'name': cookie['name'],
        'value': cookie['value'],
        'path': '/',
        'expires': None
    })
# 再次访问页面,便可实现免登陆访问
self.browser.get('http://xxx.com')
 
 
1
1
 
 
 
« Previous: the Selenium PhantomJS modification request header (Headers)
@. Posted 2017-06-27 13:10   ZhaoYingJie   reading ( 17224 ) Comments ( 1 edit   collections

Sometimes necessary when webDriver visit the Web site, with cookie achieve free access to the landing, the following is a simple implementation.

Log in and save cookie

'''
前面部分代码用于填写登录信息并登录
'''
# 获取cookie并通过json模块将dict转化成str
dictCookies = self.browser.get_cookies()
jsonCookies = json.dumps(dictCookies)
# 登录完成后,将cookie保存到本地文件
with open('cookies.json', 'w') as f:
    f.write(jsonCookies)

Read cookie achieve free access landing

# 初次建立连接,随后方可修改cookie
self.browser.get('http://xxxx.com')
# 删除第一次建立连接时的cookie
self.browser.delete_all_cookies()
# 读取登录时存储到本地的cookie
with open('cookies.json', 'r', encoding='utf-8') as f:
    listCookies = json.loads(f.read())
for cookie in listCookies:
    self.browser.add_cookie({
        'domain': '.xxxx.com',  # 此处xxx.com前,需要带点
        'name': cookie['name'],
        'value': cookie['value'],
        'path': '/',
        'expires': None
    })
# 再次访问页面,便可实现免登陆访问
self.browser.get('http://xxx.com')

Guess you like

Origin www.cnblogs.com/du-jun/p/12298102.html