自己负责的一个项目接口有token验证,登录功能(获取token)是相当于一个通用的第三方,点击登录按钮跳转公共的登录平台,登录完后再跳转回来。所以导致本地开发的时候,无法登录完后,直接跳回本地页面。
所以最开始都是手动在测试环境登录,复制浏览器的token,粘贴到本地,每次手动复制有点麻烦,就想到了python脚本自动登录并获取到token写入本地文件。
import json
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
def login_fr(url, username, password):options = webdriver.ChromeOptions()options.add_experimental_option('detach', True)driver = webdriver.Chrome(options=options)#打开登录页面driver.get('https://baidu.com')time.sleep(2)# 点击登录按钮,跳转第三方通用登录页面login1_btn = driver.find_element(By.CLASS_NAME, "login_loginBtn_esRBZ")login1_btn.click()time.sleep(2)# 获取用户名,密码,登录按钮的dom元素,填入账号,密码,并点击登录按钮user_input = driver.find_element(By.ID, "basic_mobile").send_keys(username)pw_input = driver.find_element(By.ID, "basic_password").send_keys(password)login_btn = driver.find_element(By.CLASS_NAME, "loginButton")time.sleep(2)login_btn.click()time.sleep(2)return driverif __name__ == '__main__':#这里是第三方登录地址,填入的账号及密码aim_url = {'url': 'https://baidu.com','username': '123456789','password': 'qwe123'}driver = login_fr(aim_url['url'], aim_url['username'], aim_url['password'])time.sleep(1)#将获取到的token填入本地def alter(file,session,xsrf):file_data = ""with open(file, "r", encoding="utf-8") as f:for line in f:if session in line:line = " Cookie.set('SESSION', '" + driver.get_cookies()[1]["value"] + "')" + "\n"if xsrf in line:line = " Cookie.set('XSRF-TOKEN', '" + driver.get_cookies()[0]["value"] + "')" + "\n" file_data += linewith open(file,"w",encoding="utf-8") as f:f.write(file_data)alter("D:/work/myProject/src/main.js", "Cookie.set('SESSION'", "Cookie.set('XSRF-TOKEN'")from selenium import webdriver