【发布时间】:2021-05-23 14:54:33
【问题描述】:
我正在尝试从 CAPTCHA 图片中提取文本。这个想法是使用 lxml 从表单中获取图像数据。图像数据前面带有定义数据类型的标头。我猜CAPTCHA picture 是用Base64 编码的PNG 图像。图像数据从 Base64 解码为初始二进制格式。同时PIL 在传递给PIL.Image 类之前用BytesIO 包装二进制数据。
这是 sn-p 的第一部分。
import lxml.html
import urllib.request as urllib2
import pprint
import http.cookiejar as cookielib
from io import BytesIO
import lxml.html
from PIL import Image
import pytesseract
def parse_form(html):
tree = lxml.html.fromstring(html)
data = {}
for e in tree.cssselect('form input'):
if e.get('name'):
data[e.get('name')] = e.get('value')
return data
REGISTER_URL = 'http://tracuunnt.gdt.gov.vn/tcnnt/mstdn.jsp'
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
html = opener.open(REGISTER_URL).read()
form = parse_form(html)
这里,这个函数引发OSError: cannot identify image file <_io.BytesIO object at 0x08B3B060>:
def get_captcha(html):
tree = lxml.html.fromstring(html)
img_data = tree.cssselect('div img')[0].get('src')
img_data = img_data.partition('-')[-1]
binary_img_data = img_data.decode('base64')
file_like = BytesIO(binary_img_data)
img = Image.open(file_like)
return img
img = get_captcha(html)
我怀疑它是 binary_img_data 变量。我已经尝试阅读有关如何 PIL 可能读取基于 Web 的图像(即 CAPTCHA)的解码、编码、PIL 文档和二进制数据,但没有任何帮助。
【问题讨论】:
标签: python web-scraping python-imaging-library captcha decoding