0
点赞
收藏
分享

微信扫一扫

使用selenium爬验证码图片并识别

北溟有渔夫 2022-02-22 阅读 83

1 爬验证码图片

1.1 方法一

这种方法是对方将验证码图片的url放在了<img>中,可以先将这个url提取出来,然后将这个图片下载到本地。

from bs4 import BeautifulSoup
from urllib.request import urlretrieve
from selenium import webdriver
driver = webdriver.Edge()      # Edge浏览器
driver.get("你的url")
bf=BeautifulSoup(driver.page_source, 'html.parser')
purl=bf.find(class_='图片的class name')
img_url=purl.img["src"] #获得图片的url
urlretrieve(url=img_url,filename="captcha.jpg") #保存到本地,名为captcha.jpg

1.2 方法二

有的时候找不到对方验证码图片的url,我们只能靠自己提取,这种方法是使用截图,把验证码截取出来。

from selenium import webdriver
driver = webdriver.Edge()      # Edge浏览器
driver.get("你的url")
imgelement = driver.find_element_by_xpath('验证码的xpath')
imgelement.screenshot('captcha.jpg')  #保存验证码截图

2 识别验证码

识别验证码我主要使用超级鹰,网址:https://www.chaojiying.com/,先注册一个账号,记住用户名和密码,-》进入用户中心,-》点击软件ID,-》点击生成一个软件ID,填表生成一个,记住这个软件ID。(使用需要账户题分,可以免费先领1000分)

"""
用于与超级鹰连接
"""
import requests  # 网络请求模块
from hashlib import md5  # 加密


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  # 软件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()

"""
验证码识别
"""
chaojiying = Chaojiying_Client('用户名', '密码', '软件ID')
im = open('captcha.jpg', 'rb').read()
r = chaojiying.PostPic(im, 1902) #1902 验证码类型
if r["err_str"] == "OK":
	print("验证码为: "+r["pic_str"])
举报

相关推荐

0 条评论