from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time,os,json
driver = webdriver.Chrome()
url = "https://www.cnblogs.com/"
driver.get(url)
driver.maximize_window()
def login():
driver.find_element_by_xpath('//*[@id="span_userinfo"]/a[1]').click()
driver.find_element_by_id('LoginName').send_keys('wenjing2019')
driver.find_element_by_id('Password').send_keys('*****')
driver.find_element_by_id('submitBtn').click()
#保存cookies到文件中
save_cookies_to_file(driver)
#获取cookies并保存cookies
def save_cookies_to_file(driver):
#获取存储cookies的文件夹
file_path = get_cookies_dir()
#获取cookies
cookies = driver.get_cookies()
#存储cookies到文件中
with open (file_path +"cnblogs.cookies","w") as f:
json.dump(cookies,f)
def get_cookies_dir():
project_path = os.path.dirname(os.getcwd())
file_path = project_path + "/cookies/"
if not os.path.exists(file_path):
os.mkdir(file_path)
return file_path
def check_cookies():
#设置一个登录状态,初始值是未登录
login_status = False
#将cookies信息保存到driver中
driver = save_cookies_to_driver()
#进行跳转链接的检测
driver.get("https://home.cnblogs.com/u/wenjing2019/")
current_url = driver.current_url
if current_url == "https://home.cnblogs.com/u/wenjing2019/":
login_status =True
return login_status
else:
return login_status
#保存cookies到driver中
def save_cookies_to_driver():
cookies_file = get_cookies_file()
cn_cookies_file = open(cookies_file,"r")
cn_cookies_str = cn_cookies_file.readline()
cn_cookies_dict = json.loads(cn_cookies_str)
#这里必须清除旧的cookies
driver.get('https://www.cnblogs.com/')
driver.delete_all_cookies()
for cookie in cn_cookies_dict:
driver.add_cookie(cookie)
return driver
def get_cookies_file():
return get_cookies_dir() +"cn.cookies"
if __name__=="__main__":
try:
#循环查看登录状态,判断登录是否成功
loop_status = True:
while loop_status:
#检验cookies是否生效
login_status = check_cookies()
if login_status:
loop_status = False #跳出循环
else:
login()
#跳转页面
to_page(driver)
finally:
time.sleep(2)
driver.quit()