1,登录网页,使用webdriver的get_cookies获取cookie,并保存json文件
2,读取json文件,遍历添加网站使用的每一个cookies的name,value
. 使用add_cookie添加cookie
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/6 17:58
# @Author : mrwuzs
# @Site :
# @File : cookiesAction.py
# @Software: PyCharm
import json
from public.common import pyselenium
from config import globalparam
from public.appModel.loginAction import Login
#cookie的存储路径
cookie_path = globalparam.cookie_path + "\cookies.json"
def get_cookie(username,password):
dr = pyselenium.PySelenium(globalparam.browser)
dr.max_window()
Login(dr).login(username, password)
cookies = dr.origin_driver.get_cookies()
jsonCookies = json.dumps(cookies)
with open(cookie_path, 'w') as f:
f.write(jsonCookies)
def add_cookie(dr):
dr.origin_driver.delete_all_cookies()
with open(cookie_path, 'r', encoding='utf-8') as f:
listCookies = json.loads(f.read())
for cookie in listCookies:
print(cookie)
dr.origin_driver.add_cookie({
'domain': cookie['domain'],
'name': cookie['name'],
'value': cookie['value'],
'path': '/',
'httpOnly': False,
'secure': False
})
return dr
if __name__ == '__main__':
get_cookie("username","password")
问题记录:
1,需要下打开一个url,才能添加cookie,否者会出现以下错误
selenium.common.exceptions.InvalidCookieDomainException: Message: Document is cookie-averse