import json
import time
from selenium.webdriver import ActionChains
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
url = "https://www.qcc.com/user_login?back=%2F"
options = Options()
# 无界面启动浏览器
options.add_argument('--headless')
driver = webdriver.Firefox(options=options)
wait = WebDriverWait(driver, 20, 0.5)
driver.get(url)
time.sleep(1)
# 点击密码登入
locator = (By.ID, 'normalLogin')
wait.until(EC.presence_of_element_located(locator))
driver.find_element_by_id('normalLogin').click()
time.sleep(1)
# 输入账号密码
locator = (By.ID, 'nameNormal')
wait.until(EC.presence_of_element_located(locator))
driver.find_element_by_id('nameNormal').send_keys('**你的账号**')
driver.find_element_by_id('pwdNormal').send_keys('**你的密码**')
# 获取滑块
locator = (By.ID, 'nc_1_n1z')
wait.until(EC.presence_of_element_located(locator))
button = driver.find_element_by_id('nc_1_n1z')
# 滑动滑块
ActionChains(driver).click_and_hold(button).perform()
ActionChains(driver).move_by_offset(xoffset=308, yoffset=0).perform()
ActionChains(driver).release().perform()
# 判断登录是否成功
locator = (By.XPATH, '//*[@id="nc_1__scale_text"]//*[contains(text(),"验证通过")]')
wait.until(EC.presence_of_element_located(locator))
print('-- 验证通过 --')
# 点击登录
time.sleep(1)
locator = (By.XPATH, '//*[@id="user_login_normal"]/button')
wait.until(EC.presence_of_element_located(locator))
driver.find_element_by_xpath('//*[@id="user_login_normal"]/button').click()
time.sleep(2)
# 获取cookie并通过json模块将dict转化成str
dictCookies = driver.get_cookies()
jsonCookies = json.dumps(dictCookies)
print(dictCookies)
print(jsonCookies)
# 后续使用这个cookies实现免密登录
# 关闭浏览器
driver.close()
备注:使用火狐浏览器驱动可以减去浏览器检测的烦恼。但是火狐有个致命弱点,就是每个元素操作之前最好都检测存不存在。