温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python爬虫遇到验证码怎么解决

发布时间:2021-11-25 11:17:05 来源:亿速云 阅读:227 作者:iii 栏目:大数据

本篇内容介绍了“Python爬虫遇到验证码怎么解决”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

一 前言

中国知网的注册页面使用的是这种验证码,页面如下:

Python爬虫遇到验证码怎么解决

二 准备工作

1 目标

以知网的验证码为例,利用OCR(Optical Character Recognition 光学字符识别)技术识别图形验证码。

2 安装tesseract

2.2 下载tesseract-ocr-setup-3.05.01.exe

2.3 安装注意事项

勾选Additional language data(download)选项,这样可以识别多国语言。

3 安装tesserocr

pip install tesserocr pillow

安装好的Tesseract-OCR后,从D:\Program Files (x86)\Tesseract-OCR目录下,将tessdata文件夹拷贝到下面目录

E:\WebSpider\venv\Scripts

4 获取验证码

将验证码图形 保存到本地,命名为code.jpg

三 实战

1 实战

1.1 代码

import tesserocr
from PIL import Image
 
image = Image.open('code.jpg')
result = tesserocr.image_to_text(image)
print(result)
 
image = Image.open('code1.jpg')
result = tesserocr.image_to_text(image)
print(result)
 
image = Image.open('code2.jpg')
result = tesserocr.image_to_text(image)
print(result)

1.2 效果

E:\WebSpider\venv\Scripts\python.exe E:/WebSpider/8_1.py
DTKD
JR42
PFRT

1.3 说明

code.jpg是DTKT

code1.jpg是JR42

code2.jpg是PFRT

将结果和实际图片进行比较,正确率还是比较高的。

2 实战2

2.1 代码

import tesserocr
 
print(tesserocr.file_to_text('code.jpg'))
print(tesserocr.file_to_text('code1.jpg'))
print(tesserocr.file_to_text('code2.jpg'))

2.2 效果

E:\WebSpider\venv\Scripts\python.exe E:/WebSpider/8_1.py
DTKD
.ll?42
FFKT

2.3 说明

code.jpg是DTKT

code1.jpg是JR42

code2.jpg是PFRT

将结果和实际图片进行比较,正确率并不是很高。

3 实战3

3.1 代码

import tesserocr
from PIL import Image
 
image = Image.open('code2.jpg')
 
image = image.convert('L')
threshold = 127
table = []
for i in range(256):
    if i < threshold:
        table.append(0)
    else:
        table.append(1)
 
image = image.point(table, '1')
image.show()
 
result = tesserocr.image_to_text(image)
print(result)

3.2 效果

E:\WebSpider\venv\Scripts\python.exe E:/WebSpider/8_1.py
PFRT

“Python爬虫遇到验证码怎么解决”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI