python selenium实现12306自动登录(自动验证)

2 篇文章 0 订阅
1 篇文章 0 订阅

效果图
在这里插入图片描述
验证部分交给了http://littlebigluo.qicp.net:47720/
博主littlebigluo已经训练好了CNN分类器,所以获取验证图像后直接requests.post图片到littlebigluo的服务器,通过CNN前传返回验证结果到浏览器。
不要频繁访问,服务器处理速度不够
思路很简单直接按__call__函数中的函数调用流程走就行

#coding:u8

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import requests
import base64
import re
import time

class Demo():
	def __init__(self):
		self.coordinate=[[-105,-20],[-35,-20],[40,-20],[110,-20],[-105,50],[-35,50],[40,50],[110,50]]
	def login(self):
		login_url="https://kyfw.12306.cn/otn/resources/login.html"
		driver = webdriver.Chrome()
		driver.set_window_size(1200, 900)
		driver.get(login_url)
		account=driver.find_element_by_class_name("login-hd-account")
		account.click()
		userName=driver.find_element_by_id("J-userName")
		userName.send_keys("531218020@qq.com")
		password=driver.find_element_by_id("J-password")
		password.send_keys("***********")
		self.driver=driver
	def getVerifyImage(self):
		try:
			
			img_element =WebDriverWait(self.driver, 100).until(
				EC.presence_of_element_located((By.ID, "J-loginImg"))
				)

		except Exception as e:
			print(u"网络开小差,请稍后尝试")	
		base64_str=img_element.get_attribute("src").split(",")[-1]
		imgdata=base64.b64decode(base64_str)
		with open('verify.jpg','wb') as file:
			file.write(imgdata)
		self.img_element=img_element
	def getVerifyResult(self):
		url="http://littlebigluo.qicp.net:47720/"
		response=requests.request("POST",url,data={"type":"1"},files={'pic_xxfile':open('verify.jpg','rb')})
		result=[]
		print(response.text)
		for i in re.findall("<B>(.*)</B>",response.text)[0].split(" "):
			result.append(int(i)-1)
		self.result=result
		print(result)
	def moveAndClick(self):
		try:
			Action=ActionChains(self.driver)
			for i in self.result:
				Action.move_to_element(self.img_element).move_by_offset(self.coordinate[i][0],self.coordinate[i][1]).click()
			Action.perform()
		except Exception as e:
			print(e.message())
	def submit(self):
		self.driver.find_element_by_id("J-login").click()
	def __call__(self):
		self.login() 
		time.sleep(3)
		self.getVerifyImage()
		time.sleep(1)
		self.getVerifyResult()
		time.sleep(1)
		self.moveAndClick()
		time.sleep(1)
		self.submit()
		time.sleep(10000)
		
Demo()()

后续自动刷票抢票功能实现参见https://blog.csdn.net/weixin_38283159/article/details/86508735

  • 11
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 16
    评论
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值