【问题标题】:PILLOW throws `OSError: cannot identify image file <_io.BytesIO object at 0x08B3B060>`PILLOW 抛出`OSError: cannot identify image file <_io.BytesIO object at 0x08B3B060>`
【发布时间】: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 &lt;_io.BytesIO object at 0x08B3B060&gt;

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


【解决方案1】:

要解码 base64 字符串,请尝试以下操作:

from base64 import b64decode

binary_img_data = b64decode(img_data)

您的代码使用的方法 (img_data.decode('base64')) 在 Python 2 中有效,但在 Python 3 中无效。

【讨论】:

  • 谢谢,但它给出了错误OSError: cannot identify image file &lt;_io.BytesIO object at 0x0885B270&gt;
【解决方案2】:

一开始完全忽略了解决方案。 PILLOW 无法使用该逻辑读取二进制数据中的图像,所以我简单地调用了带有图像二进制形式的request.get() 的内容,并调用 Pillow 以使用BytesIO() 即时打开它。

import lxml.html
import urllib.request as urllib2
from io import BytesIO
import lxml.html
from PIL import Image



   img_data = tree.cssselect('div img')[0].get('src')
   img_link = 'http://tracuunnt.gdt.gov.vn'+ img_data
   response = requests.get(img_link)
   img = Image.open(BytesIO(response.content))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多