最近接触了一些selenium模块的相关知识,觉得还挺有意思的,于是决定亲自尝试写一些爬虫程序来强化selenium模块(一定要多尝试、多动手、多总结)。本文主要使用python爬虫来模拟登录铁路12306官网。这儿得吐槽一句,铁路12306网站的反爬机制做的还是比较好。特别是12306的验证码很是令人很头疼的事,有时候自己去验证都不一定能通过。接下来就使用selenium模块解决验证码。

实现过程

首先通过selenium创建一个浏览器,并通过向页面嵌入js代码去掉webdriver控件(我前面有讲过,不懂的大神们可以去看我写的文章)如果不嵌入js代码就会被webdriver控件检测出,不管你怎么滑动滑块都是失败的。

# 绕过window.navigator.webdriver控件检测
option = Options()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
option.add_argument('--disable-blink-features=AutomationControlled')driver = webdriver.Chrome(options=option)
driver.maximize_window()# 切换到账号密码登录窗口
driver.get('https://kyfw.12306.cn/otn/resources/login.html')
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[2]/div[2]/ul/li[2]/a').click()
time.sleep(2)

嵌入js代码这样就不会被12306检测到是使用selenium自动化登录了。

我们先解决最难的验证码。为了实现自动化登录我们使用超级鹰打码平台。

  • 注册并登录超级鹰账号:点击链接进行注册https://www.chaojiying.com/user/login/;
  • 点击购买题分,并进行充值;
  • 点击软件id,创建一个软件Id(程序中会用到);

自动去帮我们去识别验证码。

# 初始化超级鹰
chaojiying = Chaojiying_Client('超级鹰账号', '超级鹰密码', '软件ID')  # 没有软件ID的可以去自己在超级鹰平台生成# 处理验证码
code_img_element = driver.find_element_by_xpath('//*[@id="J-loginImg"]')  # 定位到验证码的位置
# 用超级鹰去识别验证码
dic = chaojiying.PostPic(code_img_element.screenshot_as_png, 9004)  # 定位验证码并截图,调用chaojiying里的PostPic类;9004是验证码类型
result = dic['pic_str']  # x1,y1|x2,y2;超级鹰返回回来的数据是json格式的
rs_list = result.split("|")
for rs in rs_list:p_temp = rs.split(",")x = int(p_temp[0])  # 拿到的是"x"而不是xy = int(p_temp[1])# 要让鼠标移动到某一个位置,然后进行点击ActionChains(driver).move_to_element_with_offset(code_img_element, x, y).click().perform()  # 提交事件;以element为原点移动鼠标去点击验证码

验证码有可能需要我们点击多个,所以通过打码平台会得到多个坐标,就比如这种,需要点击两次,通过超级鹰就会得到两个坐标。如下图。我们发现有两个坐标会有一个“|”,有三个坐标就有两个“|”,所以我们就把他们split下,让每个坐标嵌套再一个列表里。我们得到了验证码的坐标,下一步就是去点击验证码。但是,这个坐标是相对于验证码的图片的坐标,我们必须用ActionChains来移动一下动作链的位置。详细的输出过程如下图

最最后就是比较简单的传输账号密码登录了

# 输入用户名和密码
driver.find_element_by_xpath('//*[@id="J-userName"]').send_keys('账号')
driver.find_element_by_xpath('//*[@id="J-password"]').send_keys('密码')
# 点击登录按钮
driver.find_element_by_xpath('//*[@id="J-login"]').click()
time.sleep(4)# 移动滑块
btn = driver.find_element_by_xpath('//*[@id="nc_1_n1z"]')
ActionChains(driver).drag_and_drop_by_offset(btn, 300, 0).perform()  # 拖拽滑块向右移动300像素

这个代码是超级鹰提供的接口。我封装成一个类了。

#!/usr/bin/env python
# coding:utf-8import requests
from hashlib import md5class Chaojiying_Client(object):def __init__(self, username, password, soft_id):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)',}def PostPic(self, im, codetype):"""im: 图片字节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()def ReportError(self, im_id):"""im_id:报错题目的图片ID"""params = {'id': im_id,}params.update(self.base_params)r = requests.post('http://upload.chaojiying.net/Upload/ReportError.php', data=params, headers=self.headers)return r.json()if __name__ == '__main__':chaojiying = Chaojiying_Client('超级鹰账号', '超级鹰密码', '96001')    #用户中心>>软件ID 生成一个替换 96001im = open('a.jpg', 'rb').read()                                                  # 本地图片文件路径来替换 a.jpg 有时WIN系统须要//print(chaojiying.PostPic(im, 1902))                                              # 1902 验证码类型 官方网站>>价格体系 3.4+版 print 后要加()

下面是selenium登录的代码

from selenium import webdriver
import time
from chaojiying import Chaojiying_Client
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options# 初始化超级鹰
chaojiying = Chaojiying_Client('超级鹰账号', '超级鹰密码.', '软件ID')# 绕过window.navigator.webdriver控件检测
option = Options()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
option.add_argument('--disable-blink-features=AutomationControlled')driver = webdriver.Chrome()
driver.maximize_window()driver.get('https://kyfw.12306.cn/otn/resources/login.html')
time.sleep(3)
driver.find_element_by_xpath('/html/body/div[2]/div[2]/ul/li[2]/a').click()
time.sleep(2)
# 处理验证码
code_img_element = driver.find_element_by_xpath('//*[@id="J-loginImg"]')
# 用超级鹰去识别验证码
dic = chaojiying.PostPic(code_img_element.screenshot_as_png, 9004)
result = dic['pic_str']  # x1,y1|x2,y2
rs_list = result.split("|")
for rs in rs_list:p_temp = rs.split(",")x = int(p_temp[0])  # 拿到的是"x"而不是xy = int(p_temp[1])# 要让鼠标移动到某一个位置,然后进行点击ActionChains(driver).move_to_element_with_offset(code_img_element, x, y).click().perform()  # 提交事件# 输入用户名和密码
driver.find_element_by_xpath('//*[@id="J-userName"]').send_keys('12306账号')
driver.find_element_by_xpath('//*[@id="J-password"]').send_keys('12306密码')
# 点击登录按钮
driver.find_element_by_xpath('//*[@id="J-login"]').click()
time.sleep(4)# 移动滑块
btn = driver.find_element_by_xpath('//*[@id="nc_1_n1z"]')
ActionChains(driver).drag_and_drop_by_offset(btn, 300, 0).perform()

使用selenium解决12306的登录问题相关推荐

  1. python用selenium 验证码图片_Python +Selenium解决图片验证码登录或注册问题(推荐)

    1. 解决思路 首先要获得这张验证码的图片,但是该图片一般都是用的js写的,不能够通过url进行下载. 解决方案:截图然后根据该图片的定位和长高,使用工具进行裁剪 裁剪完毕之后,使用工具解析该图片. ...

  2. Python+Selenium实现12306模拟登录

    最近在学python爬虫,学习到了selenium的使用,看网上有很多使用selenium模拟登录12306网站的文章,于是自己也尝试了一下.期间遇到了一些问题,也参考了很多大佬的文章最终得到了解决, ...

  3. 基于selenium实现12306的登录操作(图形验证码识别)

    说明 12306 会有如下一个图形验证码识别点击,所以必须得先点击正确图片,才能继续进行操作. 基本步骤 selenium打开对应网站,并进行截图 将图片截取出对应验证码所在图片 通过超级鹰识别出要点 ...

  4. 12-基于selenium实现12306模拟登录,及京东登录滑动缺口验证模拟登录

    流程分析: 使用selenium打开登录页面 对当前selenium打开的这张页面进行截图 对当前图片的局部区域(验证码图片区域)进行截图 这样验证码图片和模拟登录进行所显示的图片一一对应(如果我们对 ...

  5. python+selenium实现12306自动登录刷票抢票(自己做黄牛?!)

    上一篇写了12306的自动登录破解验证图https://blog.csdn.net/weixin_38283159/article/details/86498159 这篇算是它的后续部分加上了简单的刷 ...

  6. selenium实现12306火车购票网站滑块自动验证登录

    解决滑块验证登录问题和网站禁止selenium操作无法通过验证问题,问题过程如下,亲测有效: 当输入账号密码,点击登录后出现如下滑动解锁框: 此时,完成滑块自动滑动至右边解锁,写个拖动滑块的函数 mo ...

  7. selenium处理12306登录

    selenium处理12306登录 使用edge浏览器驱动 from selenium.webdriver import Edge from selenium.webdriver.common.act ...

  8. selenium模拟12306登录

    #!/usr/bin/env python # coding:utf-8 import requests from hashlib import md5 from selenium import we ...

  9. python+selenium 爬取微博(网页版)并解决账号密码登录、短信验证

    使用python+selenium 爬取微博 前言 为什么爬网页版微博 为什么使用selenium 怎么模拟微博登录 一.事前准备 二.Selenium安装 关于selenium 安装步骤 三.sel ...

最新文章

  1. 为什么我害怕数据结构学得好的程序员?
  2. 初学Python——文件操作第三篇
  3. feign调用如何传递token_走进Spring Cloud之五 eureka Feign(服务调用者)
  4. python 导出大量数据到excel_怎么在python中将大量数据导出到Excel文件
  5. stringredistemplate设置过期时间_Redis的过期删除策略和内存淘汰机制
  6. SSRS:之为用户“NT AUTHORITY\NETWORK SERVICE”授予的权限不足,无法执行此操作。 (rsAccessDenied)...
  7. 批处理call和start
  8. 调用图灵机器人API实现简单聊天
  9. 5006.c++类中使用static变量bug
  10. ubuntu 18.04 melodic roslaunch :七步使用roslaunch控制两个终端机器人
  11. Docker 删除所有容器和镜像,从头来过!
  12. CSS中伪类选择器及伪元素
  13. win10无线投屏_win10投屏快捷键无需频繁插拔
  14. Arduino UNO测试BME280温湿度气压传感器
  15. goahead(嵌入式Web服务器)之cgi篇
  16. DICOM VR数据类型表
  17. 毕业论文课题研究背景怎么写?
  18. Origin 2017 调整默认字体的方法
  19. 济南python工资一般多少-济南十大python编程培训机构排行榜
  20. 曾鹏锦老师:具备这5种能力人生之路越来越好走越走越宽

热门文章

  1. 人生感悟,心灵的独白
  2. win10下安装win7双系统
  3. 30天敏捷结果(12):效率角色-你是启动者还是完成者?
  4. 三子棋(井字棋)的实现
  5. 拼图软件那个好用?好用的拼图软件分享
  6. java拼图游戏设计文档_基于JAVA的拼图游戏的设计与实现(含录像)
  7. 使用APM破解Imminent rat病毒后我们学到的东西
  8. 数据库作业3:第二章课后题(关系数据库及相关概念)
  9. SouthernBiotech 艾美捷Fluoromount-G功能参数
  10. Power Pivot报错:应用程序的组件中发生了未经处理的异常