import os
from selenium import webdriver
import time,json
class Cookie(object):
def __init__(self,driver,login_url,url,web_name):
self.driver = driver
self.login_url = login_url
self.url = url
self.web_name = web_name
def is_login(self):
self.get_content(self.url)
if self.url != self.driver.current_url:
self.login(self.login_url)
def login(self,login_url):
self.driver.get(login_url)
time.sleep(20) # 在此时输入用户名和密码
cookies = driver.get_cookies()
f1 = open(self.web_name+'.txt', 'w')
f1.write(json.dumps(cookies))
f1.close()
self.get_content(self.url)
def get_content(self,url):
if os.path.exists(self.web_name+".txt"):
self.driver.delete_all_cookies()
self.driver.get(url)
print(url)
with open(self.web_name+'.txt') as f:
cookie = json.loads(f.read())
for c in cookie:
if 'expiry' in c:
del c['expiry']
print(c)
driver.add_cookie(c)
self.driver.get(url)
if __name__ == "__main__":
driver = webdriver.Chrome()
driver.maximize_window()
web_name = "bokeyuan"
login_url = "https://account.cnblogs.com/signin"
url = 'https://i-beta.cnblogs.com/'
ck = Cookie(driver,login_url,url,web_name)
ck.is_login()
#time.sleep(30)
#driver.quit()