DSMall实训案例-登录并爬取Cookie
from captcha import init_browser
from captcha import get_captcha_code
from selenium.webdriver.common.by import By
import time
# 初始化浏览器
driver = init_browser()
# 窗口最大化
driver.maximize_window()
# 打开网站首页 http://localhost:81/
driver.get('http://localhost:81/admin/')
# 设置隐式等待:在查找任何元素时,如果没找到,最多等待10秒
driver.implicitly_wait(3)
# 输入账号、密码、验证码,点击登录
def login():
# 用户名/手机号
driver.find_element(By.NAME, 'admin_name').clear()
driver.find_element(By.NAME, 'admin_name').send_keys('admin')
# 密码
driver.find_element(By.NAME, 'admin_password').clear()
driver.find_element(By.NAME, 'admin_password').send_keys('123456')
# 验证码
captcha_code = get_captcha_code(driver, (By.ID, 'change_captcha'))
driver.find_element(By.NAME, 'captcha').clear()
driver.find_element(By.NAME, 'captcha').send_keys(captcha_code)
# 点击登录
driver.find_element(By.ID, 'login_btn').click()
# 添加重试登录机制,若control元素出现在了当前页面,则说明登录成功,否则添加无限循环重试登录操作
while True:
# driver.find_elements没有找到元素时,返回空列表
control = driver.find_elements(By.LINK_TEXT, '控制台')
if len(control) > 0:
print('登录成功')
# 获取Cookie中name为PHPSESSID的Cookie值
print(driver.get_cookie('PHPSESSID'))
# 将PHPSESSIONID的value值添加到cookie.txt文件中
cookie_value = driver.get_cookie('PHPSESSID')
with open('cookie.txt', 'w') as f:
f.write(cookie_value['value'])
print('cookie已保存')
break
else:
print('登录失败,开始尝试重新登录')
login()
time.sleep(1)
time.sleep(3)DSMall实训案例-登录并爬取Cookie
https://blog.ymengze.cn//archives/dsmallshi-xun-an-li-deng-lu-bing-pa-qu-cookie