文章目录

  • 一、模拟登录“中国铁路网12306
    • 1.引入库
    • 2.初始化
    • 3.将点选验证码图片,通过人工打码,返回目标像素位置(json格式)。
    • 4.点选验证码位置得到后,需要鼠标左击进行模拟人点击。
    • 5.点选验证码+滑块验证识别登录
  • 总结

一、模拟登录“中国铁路网12306

由于12306的点选验证码机器很难识别,所以采用了人工打码平台-超级鹰;点击登录后出现的滑块验证码,用selenium.webdriver 中的ActionChains类拖动滑块。

超级鹰官网:https://www.chaojiying.com/user/

1.引入库

下面是完成本次小项目需要引入的库,导入的时候如果爆红,说明编写错误或未安装库,安装的所有过程省略。

代码如下(示例):

#!/usr/bin/env python
# coding:utf-8import requests
from PIL import Image
from io import BytesIO
from hashlib import md5
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
import time

2.初始化

包括:修改Webdriver的属性,绕过反爬检测;初始化登录超级鹰所需要的参数。

代码如下(示例):

class Login_kyfw(object):"""Python + selenium自动化工具 + 滑块验证码 + 点选验证码 + selenium识别绕过,实现模拟登录“中国铁路网12306”滑块验证码用selenium模拟人滑动,点选验证码则采用人工打码平台“超级鹰”-收费的。"""def __init__(self, username, password, soft_id):self.url = 'https://kyfw.12306.cn/otn/resources/login.html'self.driver = webdriver.Chrome()self.wait = WebDriverWait(self.driver, 20)"修改webdriver属性值,绕过反爬检测"self.driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": """Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"""})# self.script = 'Object.defineProperty(navigator, "webdriver", {get: () => false,});'# self.driver.execute_script(self.script)self.username = usernamepassword = password.encode('utf8')self.password = md5(password).hexdigest()self.soft_id = soft_idself.base_params = {'user': self.username,'pass2': self.password,'softid': self.soft_id,}self.headers = {'Connection': 'Keep-Alive','User-Agent': 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',}

3.将点选验证码图片,通过人工打码,返回目标像素位置(json格式)。

def PostPic(self, im, codetype):"""im: 图片字节,传入的点选验证码图片,通过人工打码得到目标像素(x,y)codetype: 题目类型 参考 http://www.chaojiying.com/price.html"""params = {'codetype': codetype,}params.update(self.base_params)files = {'userfile': ('ccc.jpg', im)}r = requests.post('http://upload.chaojiying.net/Upload/Processing.php', data=params, files=files, headers=self.headers)return r.json()

4.点选验证码位置得到后,需要鼠标左击进行模拟人点击。

    def click_locxy(self,dr, x, y, left_click=True):'''dr:浏览器x:页面x坐标y:页面y坐标left_click:True为鼠标左键点击,否则为右键点击'''if left_click:ActionChains(dr).move_by_offset(x, y).click().perform()else:ActionChains(dr).move_by_offset(x, y).context_click().perform()ActionChains(dr).move_by_offset(-x, -y).perform()  # 将鼠标位置恢复到移动前

5.点选验证码+滑块验证识别登录

 def slip_login(self):"12306-点击【账号登录】,切换到登录页面"self.driver.get(self.url)self.driver.maximize_window()Click = self.driver.find_element_by_xpath('/html/body/div[2]/div[2]/ul/li[2]/a')time.sleep(2)Click.click()input1 = self.driver.find_element_by_xpath('//*[@id="J-userName"]')input2 = self.driver.find_element_by_xpath('//*[@id="J-password"]')input1.send_keys('12306用户名')input2.send_keys('12306密码')"""截取12306点选验证码图片,传给人工打码平台,返回一个需要点选的目标定位列表根据定位,用click_locxy 模拟点击。"""time.sleep(3)img = self.driver.find_element_by_id('J-loginImg')locate = img.locationsize = img.sizescreenshot = self.driver.get_screenshot_as_png()screenshot = Image.open(BytesIO(screenshot))top, bottom, left, right = locate['y'], locate['y'] + size['height'], locate['x'], locate['x'] + size['width']img = screenshot.crop((left, top, right, bottom))img.save('img.png')im = open('img.png', 'rb').read()     # 本地图片文件路径 来替换 a.jpg 有时WIN系统须要//pic_str = self.PostPic(im, 9004)pic_str = pic_str['pic_str']pic_str = pic_str.split('|')pic_str = [i.split(',') for i in pic_str]print(pic_str)    # 1902 验证码类型  官方网站>>价格体系 3.4+版 print 后要加()"点击验证码"self.driver.maximize_window()for i in range(len(pic_str)):self.click_locxy(self.driver, int(pic_str[i][0])+locate['x'], int(pic_str[i][1])+locate['y'])print((int(pic_str[i][0])+locate['x'], int(pic_str[i][1])+locate['y']))self.driver.find_element_by_xpath('//*[@id="J-login"]').click()"拖动滑块完成最后登录"time.sleep(1)slip = self.driver.find_element_by_id('nc_1_n1z')slip_local = slip.locationprint(slip_local)self.click_locxy(self.driver, slip_local['x'] + 2, 0)ActionChains(self.driver).click_and_hold(on_element=slip).perform()ActionChains(self.driver).move_by_offset(xoffset=1050, yoffset=0).perform()time.sleep(5)self.driver.quit()if __name__ == '__main__':Kyfw12306 = Login_kyfw('超级鹰用户名', '超级鹰密码', '96001')    # 用户中心>>软件ID 生成一个替换 96001Kyfw12306.slip_login()

总结

文章写的优点仓促,后再进行改进,可以在下方留言哦~!

Python + selenium自动化工具 + 滑块验证码+点选验证码,实现模拟登录“中国铁路网12306”相关推荐

  1. Python Selenium.WebDriver 对Cookies的处理及应用『模拟登录』

    Python Selenium.WebDriver 对Cookies的处理及用途『模拟登录』 文章目录 Python Selenium.WebDriver 对Cookies的处理及用途『模拟登录』 一 ...

  2. selenium自动化工具(一)

    Selenium 的使用 文章预览: Selenium 的使用 1. 准备工作 2. 声明浏览器对象 3. 基本使用 4. 初始化配置 5. 查找节点 5.1 单个节点 5.2 多个节点 6. 节点交 ...

  3. python自动化办公都能做什么菜-python+selenium自动化(一)之环境搭建

    一.环境选择 python版本:python3.7(64位)下载地址:https://www.python.org/downloads/ (推荐使用官方下载) selenium版本:selenium3 ...

  4. chrome 控制台信息获取 python_【python+selenium自动化】设置Chrome启动参数

    起因:直接用selenium的webdriver启动chrome,会弹出"Chrome正在受到自动软件的控制",并且窗口较小,是因为chrome没有加载任何配置 解决:点进sele ...

  5. Python+selenium 自动化-mac下安装配置chrome驱动方法

    我的 Python 版本有两个,先通过 which 看一下对应版本的位置. 然后找到 python 安装目录里的 bin 文件夹,把对应的驱动放里面就好了. 如果不知道怎么匹配对应 chrome 版本 ...

  6. Python+selenium 自动化-基本环境搭建,调用selenium库访问百度查询天气实例演示

    Python+selenium 自动化 第一章:基本环境搭建 ① 安装 selenium 库 ② 下载对应版本的浏览器驱动 ③ 调用百度查天气演示 第一章:基本环境搭建 ① 安装 selenium 库 ...

  7. Python+selenium 自动化-读取excel记录的脚本执行登陆操作实战演示

    我们可以用 excel 来记录自动化,然后读取 excel 来执行命令,excel 可以很方便直观的管理我们录入的自动化.下面给大家演示一下 Python+selenium 自动化的实例,读取 exc ...

  8. Python+selenium自动化八大元素定位方法及实例(超详细)

    目录 一.selenium模块中的find_element_by_id方法无法使用 二.Python+selenium自动化八大元素定位方法 使用场景: 1.通过id属性定位:driver.find_ ...

  9. 亚马逊养号Selenium自动化工具介绍,配合vmlogin中文版工具试用说明

    VMLogin中文版指纹浏览器Selenium自动化工具介绍 问:VMLogin中文版 指纹浏览器自动化工具 能做什么? 答:通俗点说就是可以结合VMLogin中文版浏览器进行批量操作.养号! 能够实 ...

最新文章

  1. 迁移ADT/ANT构建的Android项目至Gradle,a walk through。
  2. 让 Python 代码更易维护的七种武器——代码风格(pylint、Flake8、Isort、Autopep8、Yapf、Black)测试覆盖率(Coverage)CI(JK)...
  3. 多媒体个人计算机能处理什么,多媒体计算机可以处理的信息类型有哪些
  4. 几种location.href的区别 js实现网页防止被iframe框架嵌套功能 .
  5. android自定义图标下载,charts
  6. 作者:林嘉洺(1992-),男,华南师范大学计算机学院硕士生。
  7. lambda表达式封装对数据库的查询
  8. php 字符串分割出数字,php 字符串分割函数的总结
  9. OpenCV精进之路(三):图像处理——形态学滤波(膨胀、腐蚀、开闭运算)
  10. python查看所有异常类_Python调试常见异常汇总
  11. js鼠标事件大全-Javascript鼠标事件大全
  12. OA系统中的HRM的发展和存在的误区,值得每一个HR学习
  13. 19 个如此好玩有趣的 Linux 命令,你玩过几个呢?
  14. 10条实用简洁的python代码,拿走即用(内附资料)
  15. Vbs调用MsAgent组件,很有趣
  16. 程序员必备 Windows 快捷操作大全
  17. axios 封装数据请求
  18. 简单两个矩阵如何用计算机运算,教你使用excel做矩阵运算
  19. 第23集丨人生的智慧:练就一颗从容自在的心
  20. c语言程序设计21点扑克牌,C语言程序设计 21点扑克牌游戏.doc

热门文章

  1. android之broadcastreceiver 耳机按键,Android 实时监听耳机按钮事件
  2. Android4.4监听耳机插入处理方法
  3. eNSP命令大全(所有命令)
  4. 欧洲共同语言参考标准英语c1,美国小学英语6级语言模块与欧洲共同语言参考标准CEFR...
  5. Nginx下载、安装与使用
  6. 容器编排工具与 Kuberneters
  7. JAVA中map集合
  8. 斯坦福CS234增强学习——(1)简介
  9. jsdelivr cdn npm替代方案
  10. 一个例程学会使用——模糊逻辑工具箱