模拟登陆 - 破解12306验证码

 12306模拟登陆demo:

在这里插入图片描述

 

用selenium来进行模拟登陆操作,主要是这个验证码部分。

https://kyfw.12306.cn/otn/resources/login.html

在这里插入图片描述

这个验证码解决的方法,可以利用机器学习。

1、让计算机能够不断在互联网上搜集不同图片和其相应的“标签”

2、经过大量图片和相应标签的训练,计算机习得了各种不同标签图片之间的差别与关系。形成一个庞大的分类器。

3、此时再向这个分类器输入一张图片。

4、分类器将输出这个图片的“标签”,图片识别过程就完毕了。

 

不过我这使用了已经写好的接口,只需要保存验证码然后post提交给接口,就可以拿到识别好的位置了。

import  requests
import numpy as np
import re,time
from PIL import Image
from selenium import webdriver
from selenium.webdriver import ActionChains


def save_img():
    driver.find_element_by_xpath('/html/body/div[2]/div[2]/ul/li[2]/a').click()
    time.sleep(2)
    img = driver.find_element_by_xpath('//*[@id="J-loginImgArea"]/img')
    location = img.location #获取验证码的x/y
    size= img.size          #获取验证码的长宽
    print(location)
    print(size)
    driver.save_screenshot('screen.png')
    i = Image.open("screen.png")
    pic_name='verify_code'+".png"#标准12306验证图片
    rangle=(int(location['x']),int(location['y']),int(location['x']+size['width']-7),int(location['y']+size['height']+2))#写成我们需要截取的位置坐标
    new_img=i.crop(rangle)#使用Image的crop函数,从截图中再次截取我们需要的区域
    new_img.save(pic_name)


def ana_pic(pic_name):
    url='http://littlebigluo.qicp.net:47720'
    files={'pic_xxfile':(pic_name,open(pic_name,'rb'),'image/png')}
    res=requests.post(url,files=files)
    list = []
    if res.status_code == 200:
        try:
            # print(res.text)
            if "图片貌似选" in res.text:
                body_str = re.findall('<B>(.*?)</B>',res.text)
                body_str = body_str[0].split(' ')
                # print(body_str)
                for i in body_str:
                    list.append(i)
                body = np.array(list)
                print("貌似是点:",body)
                return body
        except:
            return -1
    return -1


def click_one_pic(i):
    action = ActionChains(driver)
    imgelement = driver.find_element_by_xpath('//*[@id="J-loginImgArea"]/img')
    if i<=4:
        action.move_to_element_with_offset(imgelement,40+72*(i-1),73).click().perform()
    else:
        i-= 4
        action.move_to_element_with_offset(imgelement,40+72*(i-1),145).click().perform()


def click_pic(body_list):
    for i in range(len(body_list)):
        click_one_pic(int(body_list[i]))
        time.sleep(1)


if __name__ == '__main__':
    driver = webdriver.Chrome(executable_path=r'C:\chromedriver.exe')
    driver.get('https://kyfw.12306.cn/otn/resources/login.html')
    driver.maximize_window()
    save_img()
    body_list = ana_pic(pic_name='verify_code.png')
    if body_list == -1:
    	time.sleep(3)
    	ana_pic(pic_name='verify_code.png')
    click_pic(body_list)

附:原文作者文章写得很不错,大家可以去关注一波,哈哈~

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值