老师你好,无法将将cookie保存到driver中
来源:2-8 使用cookies绕过登陆

weixin_慕瓜4457392
2019-07-24
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
import os
import json
path = “C:/Users/Administrator/AppData/Local/Google/Chrome/Application/chromedriver"
driver=webdriver.Chrome(path)
def screen_shoot(driver,file_path=None):
if file_path==None:
project_path=os.path.dirname(os.getcwd())
file_path=project_path+“images"
if not os.path.exists(file_path):
os.mkdir(file_path)
image_path=time.strftime(”%Y%m%d-%H%M%S”,time.localtime())
file_path=file_path+image_path+".png"
driver.save_screenshot(file_path)
def save_cookies(driver):
project_path=os.path.dirname(os.getcwd())
file_path=project_path+"cookies"
if not os.path.exists(file_path):
os.mkdir(file_path)
#获得cookies
cookies=driver.get_cookies()
#将cookies保存到本地文件中
with open(file_path+“jd.cookies1”,“w”) as c:
json.dump(cookies,c)
print(cookies)
def login():
try:
driver.get(“https://www.jd.com”)
elem=driver.find_element_by_link_text(“理财”)
ActionChains(driver).move_to_element(elem).perform()
driver.find_element_by_link_text(“秒杀”).click()
handles=driver.window_handles
current_handle=driver.current_window_handle
for handle in handles:
if handle!=current_handle:
driver.switch_to.window(handle)
screen_shoot(driver)
driver.find_element_by_id(“key”).send_keys(“手机”)
driver.find_element_by_class_name(“button”).click()
time.sleep(3)
for handle in handles:
if handle!=current_handle:
driver.switch_to.window(handle)
screen_shoot(driver)
driver.find_element_by_class_name(“link-login”).click()
driver.find_element_by_link_text(“账户登录”).click()
driver.find_element_by_id(“loginname”).send_keys(“11111111111”)
driver.find_element_by_id(“nloginpwd”).send_keys(“111111”)
driver.find_element_by_id(“loginsubmit”).click()
#保存cookies到本地
save_cookies(driver)
finally:
time.sleep(3)
def get_url_with_cookies():
cookile_path=os.path.dirname(os.getcwd())+“cookies”+"jd.cookies1"
print(cookile_path)
cookie_file=open(cookile_path,“r”)
cookie_str=cookie_file.readline()
print(cookie_str)
#加载cookie
cookie_dict=json.loads(cookie_str)
#进入网站并删除原有cookies
driver.get(“https://www.jd.com”)
driver.delete_all_cookies()
#将cookie保存到driver中
for cookie in cookie_dict:
driver.add_cookie(cookie)
driver.get("https://order.jd.com/center/list.action")
if name==“main”:
#login()
get_url_with_cookies()
执行到 这行代码时 driver.add_cookie(cookie)
报错如下selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: invalid 'expiry’
请问这个时因为什么呢
2回答
-
大周
2019-07-27
参数类型的问题。 有可能存的时候有问题。 这个参数带一个小数点。
00 -
大周
2019-07-25
看这个错,感觉上是格式有点问题。你debug一步一步观察一下,首先看写入到文件的内容,然后再看从文件里读出来的
00
相似问题