You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python调用Appium的find_image_occurrence方法遇JSON序列化错误

解决Appium find_image_occurrence的TypeError: Object of type bytes is not JSON serializable问题

调用Appium的find_image_occurrence方法时,传入base64编码后的bytes对象触发了JSON序列化错误,错误信息如下:

raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable

问题原因

base64.b64encode()返回的是bytes类型,而Appium Python客户端在向Appium服务传递参数时,需要将参数序列化为JSON格式,但JSON不支持直接序列化bytes对象。尽管方法文档标注参数类型为bytes,实际需要的是base64编码的字符串。

解决方案

修改img_base64函数,将base64编码后的bytes对象解码为utf-8字符串:

修改后的完整代码:

import os
import base64

def img_base64(img_path):
    if os.path.exists(img_path):
        with open(img_path, 'rb') as f_obj:
            image_data = f_obj.read()
            base64_d = base64.b64encode(image_data)
            # 将bytes解码为utf-8字符串
            return base64_d.decode('utf-8')
    return None

master.save_screenshot(".\\screenshots\\test.png")

full_screenshot_base64 = img_base64(".\\screenshots\\test.png")
partial_screenshot_base64 = img_base64(".\\resource\\images\\suit_head.png")

master.update_settings({"getMatchedImageResult": True})
master.update_settings({"fixImageTemplateScale": True})

master.find_image_occurrence(base64_full_image=full_screenshot_base64, base64_partial_image=partial_screenshot_base64, visualize=True)

额外优化提示:代码中的路径\\.\\可以简化为.\\,避免不必要的转义;同时为函数添加文件不存在时的默认返回值(比如None),避免潜在的未定义返回值问题。

内容的提问来源于stack exchange,提问作者onePersonLoveCoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 02:28:09