前言:精神力量是前进的驱动

 

1.用python读取登录后的cookies,写入execl表内

2.读取excel的数据,添加到cookies中后,刷新页面

demo01:写

from selenium import webdriver
import time
import os
import xlwt
driver=webdriver.Chrome()
driver.get('-----------------------') #站址
driver.maximize_window()
driver.implicitly_wait(10)
#登录代码
........
#1.获取所有cookies
cookies=driver.get_cookies()
#2.excel的路径
current_path=os.path.dirname(__file__)
cookies_excel_path=os.path.join(current_path,'..','file','cookies.xlsx')
#3.创建一个Workbook对象
cookies_excel=xlwt.Workbook(encoding='utf-8')
#4.创建一个sheet
worksheet=cookies_excel.add_sheet('demo01')
#5.取cookies的key值, ['domain', 'httpOnly', 'name', 'path', 'secure', 'value']   #生存期Expires不加入
for cookie in cookies:
keys=list(cookie.keys())
break
# print(keys)
# print(cookies)
ncols=len(keys)
nrows=len(cookies)
#6.写入excel第1行,['domain', 'httpOnly', 'name', 'path', 'secure', 'value']
for ncol in range(ncols):
worksheet.write(0,ncol,label=keys[ncol])
style1 = xlwt.XFStyle()  # 设置单元格格式为文本
style1.num_format_str ='@'
#7.写入cookies数据
for nrow in range(1,nrows+1):
worksheet.write(nrow, 0,label=cookies[nrow-1]["domain"])
worksheet.write(nrow, 1,label=cookies[nrow-1]["httpOnly"],style=style1)
worksheet.write(nrow, 2, label=cookies[nrow-1]["name"])
worksheet.write(nrow, 3, label=cookies[nrow-1]["path"])
worksheet.write(nrow, 4, label=cookies[nrow-1]["secure"],style=style1)
worksheet.write(nrow, 5, label=cookies[nrow-1]["value"])
#8.保存excel表
cookies_excel.save(cookies_excel_path)
demo02:读
import xlrd
import os
from selenium import webdriver
import time
driver=webdriver.Chrome()
driver.get("--------------------") #站址
driver.maximize_window()
driver.implicitly_wait(10)
#文件中读取cookies信息
#1.打开表格
current_path=os.path.dirname(__file__)
cookies_excel_path=os.path.join(current_path,'..','file','cookies.xlsx')
workbook=xlrd.open_workbook(cookies_excel_path)
#2.获取sheet
sheet=workbook.sheet_by_name('demo01')
#3.读取数据
cookies_key_list=[]
nrows=sheet.nrows
ncols=sheet.ncols
for i in range(ncols):
cookies_key_list.append(sheet.cell_value(0,i))
cookies_all_list=[]
for j in range(1,nrows):
cookies_dict ={}
for c in range(len(cookies_key_list)):
if c ==1 or c==4:
cookies_dict[cookies_key_list[c]] = bool(sheet.cell_value(j, c))
else:
cookies_dict[cookies_key_list[c]] = sheet.cell_value(j, c)
cookies_all_list.append(cookies_dict)
#['domain', 'httpOnly', 'name', 'path', 'secure', 'value']
# for j in range(1,nrows):
#      cookies_dict ={}
#      cookies_dict["domain"] = sheet.cell_value(j, 0)
#      cookies_dict["httpOnly"] = bool(sheet.cell_value(j, 1))
#      cookies_dict["name"] = sheet.cell_value(j, 2)
#      cookies_dict["path"] = sheet.cell_value(j, 3)
#      cookies_dict["secure"] = bool(sheet.cell_value(j, 4))
#      cookies_dict["value"] = sheet.cell_value(j, 5)
#      cookies_all_list.append(cookies_dict)
for q in cookies_all_list:
driver.add_cookie(q)
print(q)
time.sleep(4)
driver.refresh()