方法一:手动登录系统后,F12查看页面cookies的值,键值对的形式写入代码中
add_cookie方法,实际编写时,遇到某些参数无效的报错 可以直接把对应的键值对删除,举例仅写了一行数据,实际运行需要写完整(有部分行是未发挥作用的,但需通过不断的排除才可知道哪些为必要参数)
import time
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.csdn.net/')
driver.add_cookie({'name':'log_Id_view','value':'2450','domian':'.csdn.net','path':'/','httpOnly':'FALSE','Secure':'FALSE'})#添加cookie
time.sleep(2)
driver.refresh()#刷新页面可看到已登录成功
方法二:打开验证码页等待一段时间,手工输入用户名密码验证码,点击提交或登录,print(driver.get_cookies()):打印输出cookies的值,直接从返回结果中复制
import time
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.csdn.net/')
time.sleep(30)
print(driver.get_cookies())#打印输出cookies的值,直接从返回结果中复制
方法三:将cookies写入Excel中,再读取Excel中的cookies
导入第三方模块,常用:xlwt xlrd openpy openpyxl
注意点:写入Excel中某些key的值数据类型为布尔类型,但读取时会读取为字符串类型,所以需要进行数据类型转换,转换语法可参考如下两种:
无需强制转换时报错的写法:cookie_dict['httpOnly'] = sheet.cell_value(row_num,4)
1、三元运算符转换
cookie_dict['httpOnly'] = True if sheet.cell_value(row_num,4) == 'True' else False
2、直接强制转换
cookie_dict['httpOnly'] = bool(sheet.cell_value(row_num,4))
import time
import xlrd
import xlwt
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://www.csdn.net/')
time.sleep(30)
cookies = driver.get_cookies()
#将cookies写入Excel文件
workbook = xlwt.Workbook(encoding='UTF-8')#创建workbook对象
worksheet = workbook.add_sheet('sheet1')#创建工作表sheet
worksheet.write(0,0,'name')#往表中写入内容,第一个参数为行 第二个参数为列 第三个参数为内容
worksheet.write(0,1,'value')
worksheet.write(0,2,'path')
worksheet.write(0,3,'domain')
worksheet.write(0,4,'httpOnly')
worksheet.write(0,5,'secure')
for i in range(1,len(cookies)+1): #len(cookies)取值为1,2,3,4
worksheet.write(i, 0, cookies[i-1]['name']) # 往表中写入内容,第一个参数为行 第二个参数为列 第三个参数为内容
worksheet.write(i, 1, cookies[i-1]['value'])
worksheet.write(i, 2, cookies[i-1]['path'])
worksheet.write(i, 3, cookies[i-1]['domain'])
worksheet.write(i, 4, cookies[i-1]['httpOnly'])
worksheet.write(i, 5, cookies[i-1]['secure'])
workbook.save('csdn_cookies.xls')#csdn_cookies.xls
#读取Excel文件中的cookies值
Open_workbook = xlrd.open_Open_workbook('csdn_cookies.xls')#打开Excel文件
sheet = Open_workbook.sheet_by_name('sheet1')
cookie_list = []
for row_num in range(1,sheet.nrows):
cookie_dict = {}
cookie_dict['name'] = sheet.cell_value(row_num,0)
cookie_dict['value'] = sheet.cell_value(row_num,1)
cookie_dict['path'] = sheet.cell_value(row_num,2)
cookie_dict['domain'] = sheet.cell_value(row_num,3)
cookie_dict['httpOnly'] = True if sheet.cell_value(row_num,4) == 'True' else False#三元运算转换 True是字符串类型,需要转为布尔类型 否则会报错
# cookie_dict['httpOnly'] = bool(sheet.cell_value(row_num,4))#直接强制转换 True是字符串类型,需要转为布尔类型 否则会报错
cookie_dict['secure'] = True if sheet.cell_value(row_num,5) == 'True' else False
cookie_list.append(cookie_dict)
for cookie in cookie_list:
driver.add_cookie(cookie)
time.sleep(3)
driver.refresh()#刷新页面