Selenium——根据已有cookie打开网页
原文:https://www.cnblogs.com/loveniko/p/13026269.html
一、获取cookie
#coding=utf-8
from selenium import webdriver
from PIL import Image
import time
global driver
try:
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("登录网址")
cookies = driver.get_cookies()
print("抓取前:") #此处获取的是登陆前的cookies
print(cookies)
time.sleep(20) #需要在20秒内,手动输入账号密码完成登录才会有cookies信息
cookies = driver.get_cookies()
print("抓取后:") #此处获取的是登陆后的cookies
print(cookies)
finally:
a = "n"
while a == "n":
a = input("是否关闭浏览器驱动?y/n\n")
if a == "n":
pass
else:
time.sleep(3)
driver.quit()
二、利用cookie进行登录
#coding=utf-8
from selenium import webdriver
from PIL import Image
import time
global driver
try:
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("登录网址")
coo = [抓取前的cookie,抓取后的cookie]
driver.delete_all_cookies() # 清除自带的cookie(有的网站可能不需要,本人在实测时需要添加该句代码)
for cookie in coo: #这里是将变量coo里的字典字段写到driver.add_cookie中
if 'expiry' in cookie: #expiry这个字段是指cookid的过期时间,这段代码是把'expiry'删除,不让加入到cookie中,不然会报错
del cookie['expiry']
driver.add_cookie(cookie)
time.sleep(5)
driver.refresh() #不需要输入密码,成功登陆网页
finally:
a = "n"
while a == "n":
a = input("是否关闭浏览器驱动?y/n\n")
if a == "n":
pass
else:
time.sleep(3)
driver.quit()
本博客为记录本人遇到问题时所找到的解决方案,且均经过本人亲测可用,如有侵权请联系添加来源或删除文章,谢谢。