1.python+selenium利用cookie,跳过验证码直接登录

方法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()

 

posted @ 2017-11-28 16:52  我是冰霜  阅读(1880)  评论(0编辑  收藏  举报