IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Python知识库 -> 基于selenium的python模拟登录12306 -> 正文阅读

[Python知识库]基于selenium的python模拟登录12306

新手上路,请各位大佬多多指教。

12306的反爬机制很烦,网上很多模拟登录12306的代码都过时了,

本文能通过截止日期2021.7.3的12306图片验证码和滑动验证码。

欢迎加作者微信学习交流

作者微信号:Communistic_belief

欢迎打赏,您的支持将激励一名年轻人朝着梦想不断前行。

##爬12306代码1
# coding = utf-8
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import  By
from PIL import Image  #导入Pillow模块的图像处理子模块
import time#导入time模块,用于时间处理
from chaojiying_Python.chaojiying import Chaojiying_Client
from hashlib import md5
import requests
import pyautogui
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver import ChromeOptions

pyautogui.FAILSAFE =False
pyautogui.PAUSE = 0.5
class Chaojiying_Client(object):

    def __init__(self, username, password, soft_id):
        self.username = username
        password =  password.encode('utf8')
        self.password = md5(password).hexdigest()
        self.soft_id = soft_id
        self.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()

def get_image(browser):#获取验证码图片

    browser.save_screenshot('12306.png')#截取当前页面并保存为图片
    img_page=Image.open('12306.png')#打开当前页面的截图
    img_code = img_page.crop((1259, 365, 1658, 600))  # imag_element定位的验证码图片位置有问题,手动测量坐标
    #img_element = browser.find_element(By.ID, 'J-loginImg')  # 通过标签的id属性值定位验证码图片
    #location=img_element.location#获取验证码图片的坐标
    #size=img_element.size#获取验证码图片的大小
    #left=location['x']#获取验证码图片左上角的x坐标
    #top=location['y']#获取验证码图片左上角的y坐标
    #right=left+size['width']#获取验证码右下角的x坐标
    #bottom=top+size['height']#获取验证码图片右下角的y坐标
    #img_code=img_page.crop((left,top,right,bottom))#使用crop()函数根据坐标参数裁剪当前页面的截图,得到验证码图片
    #print(left,top,right,bottom)
    img_code.save('code.png')#保存验证码图片
    return

def get_tracks(distance):
    """
    根据偏移量获取移动轨迹
    :param distance:偏移量
    :return:移动轨迹
    """
    # 移动轨迹
    tracks = []
    # 当前位移
    current = 0
    # 减速阈值
    mid = distance * 4 / 5
    # 计算间隔
    t = 0.1
    # 初速度
    v = 300
    while current < distance:
        if current < mid:
            # 加速度为正
            a = 450
        else:
            # 加速度为负
            a = -30
        # 初速度v0
        v0 = v
        # 当前速度
        v = v0 + a * t
        # 移动距离
        move = v0 * t + 1 / 2 * a * t * t
        # 当前位移
        current += move
        # 加入轨迹
        tracks.append(round(move))
    return tracks

def move_to_gap(slider, tracks):
    """
    拖动滑块
    :param slider: 滑块
    :param tracks: 轨迹
    :return:
    """
    # 模拟滑动滑块
    action = ActionChains(browser)
    action.click_and_hold(slider).perform()
    # action.reset_actions()   # 清除之前的action
    for i in tracks:
        action.move_by_offset(xoffset=i, yoffset=0).perform()
    time.sleep(0.05)
    action.release().perform()


def chaojiying(imgpath,imgtype):
    chaojiying=Chaojiying_Client('账号','密码','ID')#实际的超级鹰账号、密码和软件ID
    im=open(imgpath,'rb').read()#打开要识别的验证码图片
    return chaojiying.PostPic(im,imgtype)#根据设置的验证码类型识别验证码图片并返回结果

timeout = 20
browser = webdriver.Chrome(executable_path='chromedriver.exe')
#chrome 79以后版本selenium检测规避
browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
  "source": """
    Object.defineProperty(navigator, 'webdriver', {
      get: () => undefined
    })
  """
})
browser.get('https://kyfw.12306.cn/otn/resources/login.html')  # 访问12306的登录页面
browser.maximize_window()
wait = WebDriverWait(browser, timeout)
login_user_page = browser.find_element(By.XPATH, '/html/body/div[2]/div[2]/ul/li[2]/a')
# 通过xpath表达式定位“账号登录”按钮
login_user_page.click()  # 单击账号登录按钮
username_input = browser.find_element(By.ID, 'J-userName')  # 通过标签的id属性值定位账号输入框
password_input = browser.find_element(By.ID, 'J-password')  # 通过标签的id属性值定位密码输入框
username_input.send_keys('账号')  # 在账号输入框中输入账号,修改为实际使用的12306账号
time.sleep(2)  # 为了让模拟操作更像真实的人类用户,在两次输入之间插入时间间隔
password_input.send_keys('密码')  # 在密码框中输入密码,修改为实际使用的12306密码
get_image(browser)  # 截取验证码图片
result = chaojiying('code.png', 9004)  # 将验证码图片上传至超级鹰平台并指定验证码类型,获取识别结果
location_code = result['pic_str']  # 从识别结果中提取需要的坐标信息
print(location_code)
img_element = browser.find_element(By.ID, 'J-loginImg')  # 通过标签的id属性值定位验证码图片标签
for i in location_code.split('|'):
    x = int(i.split(',')[0])  # 获取坐标的x值
    y = int(i.split(',')[1])  # 获取坐标的y值
    x = 1259 + x
    y = 504 + y
    # screen——shot截屏的坐标原点为(0,139),
    # pyautogui的点击坐标是以电脑屏幕的最左上角为原点来说的,所以需要点击的坐标要算上浏览器的上方窗口条高度
    pyautogui.click(x, y)
login_button = browser.find_element(By.ID, 'J-login')
login_button.click()
# 获取滑动滑块
slide = wait.until(
    EC.element_to_be_clickable((By.CSS_SELECTOR,
                                'div#nc_1__scale_text > span.nc-lang-cnt'))
)
# 获取滑块滑动距离
distance = slide.size['width']
# 生成滑动轨迹
tracks = get_tracks(distance)
# 获取滑块点击按钮
slide_button = wait.until(
    EC.element_to_be_clickable((By.CSS_SELECTOR,
                                'span#nc_1_n1z'))
)
# 滑动滑块进行验证
move_to_gap(slide_button , tracks)

本文的代码实现需要超级鹰的账号和12306的账号哦,填入指定位置即可。

  Python知识库 最新文章
Python中String模块
【Python】 14-CVS文件操作
python的panda库读写文件
使用Nordic的nrf52840实现蓝牙DFU过程
【Python学习记录】numpy数组用法整理
Python学习笔记
python字符串和列表
python如何从txt文件中解析出有效的数据
Python编程从入门到实践自学/3.1-3.2
python变量
上一篇文章      下一篇文章      查看所有文章
加:2021-07-04 19:27:40  更:2021-07-04 19:28:08 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/3 11:43:43-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码