使用python的selenium自动化登录获取cookie
UI自动化时经常需要进行登录,为避免重复地进行登录操作,通过一次登录成功后获取cookie,后续直接引用cookies跳过登录
#!/usr/local/bin/python
# -*- coding: UTF-8 -*-
from selenium import webdriver # 从selenium导入webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
import json
import time
chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
# 不启动界面显示- linux下命令行模式必须启用
# chrome_options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path='C:\devtool\Anaconda\Scripts\chromedriver') # Optional argument, if not specified will search path.
driver.get('http://adnet.qq.com/index') # 获取百度页面
driver.switch_to.frame('ptlogin_iframe') # 进入iframe
# 选择账号密码登录
selElement = driver.find_element_by_id('switcher_plogin')
selElement.click()
# 输入账号密码
userElement = driver.find_element_by_id('u')
pwdButton = driver.find_element_by_id('p') #密码输入框
subButton = driver.find_element_by_id('login_button') #密码输入框
userElement.send_keys("111") #输入框输入
pwdButton.send_keys("xxx") #输入框输入
subButton.click()
# 显示等待
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "page"))
)
finally:
cookies = driver.get_cookies()
# time.sleep(5)
# driver.refresh('http://adnet.qq.com/index')
jsonCookies = json.dumps(cookie)
with open('vcyber.json', 'w') as f:
f.write(jsonCookies)
# 关闭浏览器 driver.close()
从文件中读取cookies
# coding=utf-8 def txt_cookies(file_name_): with open(file_name_, "r") as f: lines = f.readlines() lines = (line.strip() for line in lines) cookie = "".join(lines) return cookie if __name__ == '__main__': file_name = "cookies.txt" cookies = txt_cookies(file_name) print(cookies)
浙公网安备 33010602011771号