1、使用场景
登录场景,同时存在账号密码登录和钉钉扫码登录方式,绕过钉钉扫码登录
2、实现思路
先使用账号密码登录,获取cookie,然后保存信息,再访问登录地址,添加cookie
3、脱敏代码
from selenium import webdriver
import time
# driver1为首次登录网站获取到的cookie
driver1 = webdriver.Chrome()
driver1.get("http://xxx/")
driver1.maximize_window()
time.sleep(2)
#通过find_element_by_xpath的send_keys向输入框发送用户名密码登录
driver1.find_element_by_xpath('//*[@id="username"]').send_keys("12345678901")
driver1.find_element_by_xpath('//*[@id="password"]').send_keys("123456")
driver1.find_element_by_xpath('//*[@id="loginFormBtn"]').click()
time.sleep(2)
# get_cookies的方法得到登录后的cookie
savedCookies = driver1.get_cookies()
# driver2需添加driver1的cookie
driver2 = webdriver.Chrome()
driver2.get("http://xxx/")
driver2.delete_all_cookies()
# 遍历savedCookies
for cookie in savedCookies:
for k in {'name', 'value', 'domain', 'path'}:
if k not in list(cookie.keys()):
if k == 'expiry':
t = time.time()
cookie[k] = int(t)
driver2.add_cookie({k: cookie[k] for k in {'name', 'value', 'domain', 'path'}})
driver2.get("http:xxx")
print(driver2.get_cookies())