详解python 爬取12306验证码

yizhihongxing

接下来我将为你详细讲解“详解Python爬取12306验证码”的完整攻略。

1. 前言

在进行python爬虫时,验证码的破解常常是很重要的一步。而12306验证码的破解则是很多人首次接触验证码破解时的练手项目。本文将详细介绍如何使用Python来爬取12306的验证码。

2. 前置要求

在开始之前,需要满足以下前置要求:

  • 安装Python 2.X或3.X版本
  • 安装requests库
  • 安装Pillow库
  • 确定12306的验证码接口路径

3. 步骤

3.1 获取验证码图片

我们可以使用如下代码:

import requests
from PIL import Image

def get_captcha():
    url = 'https://kyfw.12306.cn/passport/captcha/captcha-image64'
    response = requests.get(url)
    img_base64 = response.json()['image']
    with open('captcha.png', 'wb') as f:
        f.write(img_base64.decode('base64'))
    img = Image.open('captcha.png')
    img.show()

if __name__ == '__main__':
    get_captcha()

在该代码中,我们首先使用requests库向12306的验证码接口请求验证码图片数据,并将返回的数据中‘image’字段保存为本地的验证码图片文件。接下来,我们使用Pillow库中的Image.open()方法打开该图片,并使用show()方法将其展示出来。

这里我使用的是requests库以及Pillow库,你也可以根据自己的需求来选择使用其他库实现同样的功能。

3.2 自动识别验证码

如果你并不想手动输入验证码,那么可以使用tesseract-OCR。tesseract-OCR作为一款OCR引擎,不仅支持识别验证码图形,还支持多种语言的识别。

安装tesseract-OCR后,我们可以在原有的代码中添加自动识别验证码的功能:

import requests
import pytesseract
from PIL import Image

def get_captcha_text():
    url = 'https://kyfw.12306.cn/passport/captcha/captcha-image64'
    response = requests.get(url)
    img_base64 = response.json()['image']
    with open('captcha.png', 'wb') as f:
        f.write(img_base64.decode('base64'))
    img = Image.open('captcha.png')
    text = pytesseract.image_to_string(img)
    return text

if __name__ == '__main__':
    captcha_text = get_captcha_text()
    print(captcha_text)

在该代码中,我们首先使用requests库向12306的验证码接口请求验证码图片数据,并将返回的数据中‘image’字段保存为本地的验证码图片文件。接下来,我们使用Pillow库中的Image.open()方法打开该图片,并使用pytesseract库中的image_to_string()方法自动识别验证码。

3.3 将识别结果提交到服务器

最后,我们可以将识别结果提交到服务器,以此完成登录过程。在该过程中,可能需要使用session等机制维持登录状态,具体操作可以参考Python的requests和cookies相关API。

示例一:

import requests
import pytesseract
from PIL import Image

def login(username, password):
    login_url = 'https://kyfw.12306.cn/otn/login/init'
    captcha_url = 'https://kyfw.12306.cn/passport/captcha/captcha-image64'
    captcha_check_url = 'https://kyfw.12306.cn/passport/captcha/captcha-check'
    headers = {
        'Host': 'kyfw.12306.cn',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
        'Referer': 'https://kyfw.12306.cn/otn/login/init'
    }
    session = requests.session()
    session.get(login_url, headers=headers)
    captcha_text = get_captcha_text()
    data = {
        'answer': captcha_text,
        'login_site': 'E',
        'rand': 'sjrand'
    }
    response = session.post(captcha_check_url, data=data, headers=headers)
    if response.json()['result_code'] == '4':
        print('验证码校验通过!')
    else:
        print('验证码校验失败!')
        return False
    data = {
        'username': username,
        'password': password,
        'appid': 'otn'
    }
    response = session.post(login_url, data=data, headers=headers)
    if response.json()['result_code'] == 0:
        print('登录成功!')
        return True
    else:
        print('登录失败!')
        return False

def get_captcha_text():
    url = 'https://kyfw.12306.cn/passport/captcha/captcha-image64'
    response = requests.get(url)
    img_base64 = response.json()['image']
    with open('captcha.png', 'wb') as f:
        f.write(img_base64.decode('base64'))
    img = Image.open('captcha.png')
    text = pytesseract.image_to_string(img)
    return text

if __name__ == '__main__':
    login('your_username', 'your_password')

在该代码中,我们使用requests库创建了一个session对象,并分别请求了登录页面、验证码图片以及验证码校验接口。在验证码校验中,我们传递了自动识别出的结果,并通过检查返回的json数据中‘result_code’字段判断验证码是否识别正确。在成功校验验证码后,我们以同样的方式提交了用户名和密码,并最终判断了登录结果(通过判断返回的json数据中‘result_code’字段)。

示例二:

import requests
import pytesseract
from PIL import Image

session = requests.session()

def get_captcha_text():
    url = 'https://kyfw.12306.cn/passport/captcha/captcha-image64'
    response = session.get(url)
    img_base64 = response.json()['image']
    with open('captcha.png', 'wb') as f:
        f.write(img_base64.decode('base64'))
    img = Image.open('captcha.png')
    text = pytesseract.image_to_string(img)
    return text

def get_cookie():
    url = 'https://kyfw.12306.cn/passport/captcha/captcha-image64'
    response = session.get(url)
    cookie = response.cookies['RAIL_EXPIRATION']
    cookie = str(int(cookie) + 60 * 60 * 24 * 30)
    return cookie

def login(username, password):
    login_url = 'https://kyfw.12306.cn/otn/login/init'
    captcha_check_url = 'https://kyfw.12306.cn/passport/captcha/captcha-check'
    headers = {
        'Host': 'kyfw.12306.cn',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Referer': 'https://kyfw.12306.cn/otn/login/init'
    }

    captcha_text = get_captcha_text()
    data = {
        'answer': captcha_text,
        'login_site': 'E',
        'rand': 'sjrand'
    }
    response = session.post(captcha_check_url, data=data, headers=headers, cookies=session.cookies.get_dict())
    if response.json()['result_code'] == '4':
        print('验证码校验通过!')
    else:
        print('验证码校验失败!')
        return False

    cookie = get_cookie()
    headers.update({
        'Cookie': 'RAIL_EXPIRATION={};RAIL_DEVICEID=your_device_id'.format(cookie)
    })

    data = {
        'username': username,
        'password': password,
        'appid': 'otn'
    }
    response = session.post(login_url, data=data, headers=headers, cookies=session.cookies.get_dict())
    if response.json()['result_code'] == 0:
        print('登录成功!')
        return True
    else:
        print('登录失败!')
        return False

if __name__ == '__main__':
    login('your_username', 'your_password')

在该代码中,我们依然是先获取并识别验证码,但是在验证码校验与登录过程中增加了许多细节操作。为了避免被封IP,我们获取了cookie中的RAIL_EXPIRATION,将其增加了30天的有效期后放回cookie中。在请求登录接口时,我们还需要将获取到的cookie作为请求头的一部分传递。

4. 总结

以上便是详解Python爬取12306验证码的攻略完整过程和示例。在实际应用中,要注意识别精度、请求频率等问题,避免被封IP。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:详解python 爬取12306验证码 - Python技术站

(0)
上一篇 2023年6月3日
下一篇 2023年6月3日

相关文章

  • Python爬虫练习汇总

    Python爬虫练习汇总攻略 Python爬虫是一种抓取网络数据的技术,也是现在比较热门的技术之一。学习Python爬虫,需要具备一定的编程基础和网络基础。下面是Python爬虫练习汇总攻略: 了解爬虫基础 在学习Python爬虫之前,需要先了解一些基础的概念或知识: 爬虫是什么?指的是通过网络来抓取网页数据的程序,可以获取各种网络数据,如HTML、XML、…

    python 2023年5月14日
    00
  • Python爬取某平台短视频的方法

    Python爬取某平台短视频的方法 爬取短视频需要用到爬虫技术,Python提供了强大的爬虫库requests和网页解析库BeautifulSoup,还有Selenium WebDriver等库,可以实现获取网页源代码、解析网页、模拟浏览器行为等操作。下面将介绍爬取某平台短视频的方法: 步骤一:分析网页 在使用Python爬取某平台短视频时,我们首先需要分析…

    python 2023年5月14日
    00
  • Python中函数的基本定义与调用及内置函数详解

    Python中函数的基本定义与调用 在Python中,函数是一段预先定义的可重用代码块,可以把一些常用的操作封装到函数中,以此来简化代码的复杂度和重复性。 Python中定义函数非常简单,用def关键词,后面紧跟函数名和圆括号,即可定义一个函数。下面是一个简单的函数定义示例: def greet(name): print(f"Hello, {nam…

    python 2023年6月5日
    00
  • python编写第一个交互程序步骤示例教程

    下面是Python编写第一个交互程序的完整攻略。 1. 确定交互程序功能 首先,需要确定交互程序的功能,例如在控制台中实现一个简单的计算器。需要考虑到程序的输入输出形式、输入输出的格式等方面。 2. 编写代码 接下来,需要根据确定的功能编写代码。在编写代码时,需要遵循编码规范,编写可读性较高的代码。如果需要读取用户的输入,可以使用 Python 的 inpu…

    python 2023年5月19日
    00
  • python中random随机函数详解

    Python中random随机函数详解 1. random模块介绍 Python标准库中的random模块提供了进行随机数生成的函数。 2. random模块中常用函数 random模块中有很多不同的函数用于生成随机数,以下是一些常用函数: random():生成一个在[0,1)范围内的随机浮点数 randint(start, end):生成一个在指定范围内…

    python 2023年6月3日
    00
  • 浅析AST抽象语法树及Python代码实现

    下面我将为你详细讲解“浅析AST抽象语法树及Python代码实现”的完整攻略。本攻略包括以下内容: 一、什么是AST抽象语法树? AST(Abstract Syntax Tree)即抽象语法树,它是将程序代码转化为树形结构的形式,树中的每个节点都表示代码中的一种结构,例如表达式、语句、函数等等。 简单来说,AST就是为了更好地描述代码结构而产生的一种数据结构…

    python 2023年6月5日
    00
  • python中的集合及集合常用的使用方法

    下面是“Python中的集合及集合常用的使用方法”完整攻略。 什么是集合 在Python中,集合是一种基本的数据结构,是一组无序的、唯一的元素的集合。Python中的集合类似于数学中的集合,因此它们支持集合的运算,如并集、交集、差集等。 集合的创建 Python中的集合用花括号 {} 表示,元素之间使用逗号分隔。例如,创建一个包含整数1、2、3的集合,可以使…

    python 2023年5月13日
    00
  • Python读取excel指定列生成指定sql脚本的方法

    Python读取excel指定列生成指定sql脚本的方法可以通过以下步骤实现: 安装依赖库 在 Python 环境下,我们需要安装 pandas 和 openpyxl 库。可以通过以下命令来安装: pip install pandas openpyxl 读取excel文件 使用 pandas 库中的 read_excel 函数读取excel文件。例如,我们有…

    python 2023年5月14日
    00
合作推广
合作推广
分享本页
返回顶部