You need to enable JavaScript to run this app. Python json.dumps序列化含WebElement的字典报TypeError,不修改原函数如何处理
优惠活动
大模型
产品
解决方案
定价
更多

Python json.dumps序列化含WebElement的字典报TypeError,不修改原函数如何处理

不修改原函数排除WebElement完成JSON序列化的实现方案

核心思路

所有操作都在拿到x()的返回值之后执行,完全不侵入x()的内部逻辑,满足不修改原函数的要求。

适配示例单层字典的快速写法

针对示例里的扁平结构字典,直接用字典推导式把值是WebElement的键值对筛掉就行:

import json
from selenium.webdriver.remote.webelement import WebElement

# 原函数原封不动调用,不做任何改动
raw_dict = x()
# 过滤掉WebElement类型的值
clean_dict = {
    k: v for k, v in raw_dict.items()
    if not isinstance(v, WebElement)
}
print(json.dumps(clean_dict, ensure_ascii=False))

多层嵌套结构的通用处理

如果返回的字典里嵌套了子字典、列表这类结构,直接遍历平层是清不干净藏在深层的WebElement的,这时候用递归过滤就行:

def strip_webelements(obj):
    # 碰到WebElement直接标记为待移除
    if isinstance(obj, WebElement):
        return None
    # 递归处理字典,把值为待移除标记的键删掉
    if isinstance(obj, dict):
        cleaned = {}
        for k, v in obj.items():
            res = strip_webelements(v)
            if res is not None:
                cleaned[k] = res
        return cleaned
    # 递归处理列表/元组,把元素为待移除标记的项删掉
    if isinstance(obj, (list, tuple)):
        cleaned_list = []
        for item in obj:
            res = strip_webelements(item)
            if res is not None:
                cleaned_list.append(res)
        return cleaned_list
    # 剩下的都是正常可序列化的类型,直接返回
    return obj

# 过滤完再序列化
clean_dict = strip_webelements(x())
print(json.dumps(clean_dict, ensure_ascii=False))

踩坑提醒

  • 导入WebElement的时候必须用正确的路径:selenium.webdriver.remote.webelement.WebElement,导错模块路径会导致isinstance判断完全失效,根本识别不到WebElement对象
  • 这里的逻辑是完全排除WebElement,不会把它的定位、文本之类的属性塞进JSON,符合排除类需求
  • 别想着用自定义JSONEncoder来实现排除,Encoder只能把不可序列化的值转成可序列化的内容,根本没法删字典里的键,做不到彻底排除的效果
  • 后面如果碰到其他要排除的自定义不可序列化对象,直接在类型判断分支里补上对应的类判断就行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.06 13:06:03