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

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

创新新互联,凭借10多年的成都网站建设、成都网站制作经验,本着真心·诚心服务的企业理念服务于成都中小企业设计网站有上千案例。做网站建设,选创新互联。

一 前言

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

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爬虫遇到验证码怎么解决”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!

名称栏目:Python爬虫遇到验证码怎么解决
文章源于:https://www.cdcxhl.com/article30/jsceso.html

成都网站建设公司_创新互联,为您提供建站公司服务器托管网页设计公司外贸建站网站建设企业网站制作

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都seo排名网站优化