1.python+selenium利用cookie,跳過驗證碼直接登入

我是冰霜發表於2017-11-28

方法1  

在登入時,叫程式碼等待一段時間,然後手動輸入驗證碼

# coding:utf-8
from selenium import webdriver
import time
url = 'http://192.168.XXX:7001/AXXXse'
driver = webdriver.Chrome()
driver.get(url)     # 進入登入首頁
driver.maximize_window()   # 視窗最大化

time.sleep(3)
driver.find_element_by_id('j_username').send_keys('admin')   #輸入賬號
driver.find_element_by_id('j_password').send_keys('abc123456')   # 輸入密碼
time.sleep(10)   # 等待10s,利用這段空隙,手動輸入驗證碼

driver.find_element_by_xpath(".//*[@id='login-tabs-item']/div/div[2]/div/div[1]/div/a[1]").click()
time.sleep(3)

driver.quit()

方法2

利用cookie記錄登入狀態,也就是跳過登入

(1)利用方法1獲取登入前和登入後的cookie資訊

# coding:utf-8
from selenium import webdriver
import time
url = 'http://192.168XXX:7001/AXXase'
driver = webdriver.Chrome()
driver.delete_all_cookies()  # 開啟瀏覽器時先清除瀏覽器存在的cookie資訊
driver.get(url)     # 進入登入首頁
driver.maximize_window()   # 視窗最大化
cookie1 = driver.get_cookies()   # 獲取登入前cookie
print(cookie1)    # 列印登入前cookie資訊
time.sleep(3)
driver.find_element_by_id('j_username').send_keys('admin')   #輸入賬號
driver.find_element_by_id('j_password').send_keys('abc123456')   # 輸入密碼
time.sleep(10)   # 等待10s,利用這段空隙,手動輸入驗證碼

driver.find_element_by_xpath(".//*[@id='login-tabs-item']/div/div[2]/div/div[1]/div/a[1]").click()
time.sleep(3)

cookie2 = driver.get_cookies()   # 獲取登入後cookie
print(cookie2)   # 列印登入後cookie資訊

driver.quit()

得到如下cookie資訊

登入前
[{'domain': '192.168.XXX', 
'httpOnly': True, 
'name': 'JSESSIONID',
 'path': '/', 
 'secure': False, 
 'value': 'DPKJhdKJ9Q6vP8KTpSqQq3hn1vJ4PlQpRBp25NXJKH2cXyx7LCGb!-1802342537'}]
 
 登入後
[{'domain': '192.168.XXX', 
'expiry': 1512457146, 
'httpOnly': False, 
'name': '49BAC005-7D5B-4231-8CEA-16939BEACD67', 
'path': '/ApprBase', 
'secure': False, 
'value': 'admin'}, 

{'domain': '192.168.XXX', 
'httpOnly': True, 
'name': 'JSESSIONID', 
'path': '/', 
'secure': False, 
'value': 'WhtVhdKZXLNDLXD0Vw8106yL776ynQ1v4G17GLgnfmggRghtMW4n!-1802342537'}]

(2)把登入後的cookie寫進瀏覽器

# coding:utf-8
from selenium import webdriver
import time
url = 'http://192.168.XXX:7001/AXXase'
driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.delete_all_cookies()   # 清除cookie

driver.get(url)
driver.maximize_window()
# 新增cookie
c1 = {'domain': '192.16XXX',
      'expiry': 1512457146,
      'httpOnly': False,
      'name': '49BAC005-7D5B-4231-8CEA-16939BEACD67',
      'path': '/ApXXe',
      'secure': False,
      'value': 'admin'}
c2 = {'domain': '192.16XX3',
      'httpOnly': True,
      'name': 'JSESSIONID',
      'path': '/',
      'secure': False,
      'value': 'QJrFhdZBKSCZtZFDVgvnDxTyKxzpP8YQThyPKnZ8RwCGWKyKJLvH!-1802342537'}

driver.add_cookie(c1)
driver.add_cookie(c2)
time.sleep(3)
# 再次登入
driver.get(url)
time.sleep(3)
driver.quit()

 

相關文章