python自动化-使用cookie实现自动登录

本文由以下几个部分组成
1.实现过程
2.环境
3.代码
4.代码优化计划
代码已优化,见具体代码
【python自动化-使用cookie实现自动登录】实现过程:

  • 打开网站——登录——获取cookie——将cookie存储到Python小型数据库——后续再需要登录时直接从本地数据库获取cookie即可
  • cookie中有时候有过期时间,可以去掉,避免登录受影响
  • 当cookie失效后,再次获取即可,此方法避免了每次都要去获取cookie,在有效期获取一次即可
  • 如果失效,重新获取即可
环境
开发环境:python+pycharm
测试网站:ceshiren.com
验证情况:有一些网站只有登录后可以查看,验证带着cookie去登录是否能访问到正确的网站即可
代码
git地址:https://github.com/karen-liu01/login_through_cookie
具体代码:
import shelve from time import sleep from selenium import webdriver from selenium.webdriver.common.by import Byclass TestDemo1: def setup(self): url = "https://ceshiren.com/t/topic/6223/21" self.driver = webdriver.Chrome() # self.driver.get(url) self.driver.get("https://ceshiren.com") self.driver.maximize_window() self.driver.implicitly_wait(5) sleep(3)def teardown(self): self.driver.quit()def get_cookies(self): self._username = "XXX" self._password = "XXX"print("打开界面点击登录按钮") self.driver.find_element(By.XPATH, "//*[@id='ember5']/header/div/div/div[2]/span/button[2]/span").click() sleep(3) print("输入用户名和密码点击登录") self.driver.find_element(By.XPATH, '//*[@id="login-account-name"]').send_keys(self._username) self.driver.find_element(By.XPATH, '//*[@id="login-account-password"]').send_keys(self._password) self.driver.find_element(By.XPATH, '//*[@id="login-button"]/span').click() sleep(7) print("获取cookie") self.driver.get("https://ceshiren.com/t/topic/4496/2") cookies = self.driver.get_cookies() print(cookies) return cookiesdef handle_cookies(self): cookies_test = self.get_cookies() print(cookies_test) db = shelve.open("cookies") db["cookie"] = cookies_test c = db["cookie"] for cookie in c: if "expiry" in cookie.keys(): cookie.pop("expiry") self.driver.add_cookie(cookie) db.close() return cdef test_login(self): db = shelve.open("cookies") cookies = db["cookie"] db.close() print(cookies) for cookie in cookies: self.driver.add_cookie(cookie) sleep(3) self.driver.get("https://ceshiren.com/t/topic/6223/21") sleep(3) print(f"***** {self.driver.title}") title = self.driver.title key = "到课率查询贴" if key in title: print("cookies有效,登录成功") assert keyin title else: print("cookies无效,需要重新获取并存储") cookies = self.handle_cookies() self.driver.get("https://ceshiren.com/t/topic/6223/21") sleep(3) title = self.driver.title assert key in title

代码优化计划
1.将cookie是否有效加一个判断,如果有效,直接登录,如果失效,再去获取即可
2.浏览器打开及退出等操作,可以放在setup和teardown中
3.username和password可以提取成变量
已优化,见代码

    推荐阅读