首页 > 解决方案 > TypeError:“发布”对象不可下标

问题描述

目前试图弄清楚为什么我不能从返回的字典中提取特定的键/值。查看这个问题,我发现这个较早的问题基本上表明该对象需要采用 json 格式才能被访问。

def Dumpster_Fire_Parser():

    import moesearch
    import pandas as pd

    trash = moesearch.search(archiver_url="https://archive.4plebs.org",
                             board="pol",
                             filter="image",
                             deleted="not-deleted",
                             )
    # trash = dict(trash)

    time_dumpster_dict = {}
    country_dumpster_dict = {}

    for i, j in enumerate(trash):

        trash_dict = j
        time_stamp = trash_dict['timestamp']
        comment = trash_dict['comment']
        country = trash_dict['poster_country_name']
        time_dumpster_dict[time_stamp] = comment
        country_dumpster_dict[time_stamp] = country

    export_frame = pd.DataFrame([time_dumpster_dict, country_dumpster_dict]).T
    export_frame.columns = ['d{}'.format(i) for i, col in enumerate(export_frame, 1)]

    print(export_frame)

    return export_frame

运行此代码会返回错误:

Traceback (most recent call last):
  File "<input>", line 17, in <module>
TypeError: 'Post' object is not subscriptable

我查看了源代码moesearch.search(),它已经转换为那里的 json 对象。

req = requests.get(url, stream=False, verify=True, params=kwargs)
  res = req.json() # How its written in source

一旦请求完成,我尝试将其显式转换为dict,trash = dict(trash)但是这会返回另一个错误:

TypeError: cannot convert dictionary update sequence element #0 to a sequence 
# Is thrown when trash = dict(trash) isn't commented out

有人遇到过这个吗?此代码是可执行的,请记住 Search API 限制为每分钟 5 个请求。其他端点不受限制。

标签: pythonpython-3.x

解决方案


在第 40 行moesearch转换为 JSON的源代码是正确的,但再往下几行,您可以看到该函数返回一个对象列表(第 44 行,语句):search()Postreturn

def search(archiver_url, board, **kwargs):
    ...
    req = requests.get(url, stream=False, verify=True, params=kwargs)
    res = req.json()
    if ArchiveException.is_error(res):
        raise ArchiveException(res)
    res = res['0']
    return [Post(post_obj) for post_obj in res["posts"]]

所以在你的代码中,trash是一个列表,j是一个类型的对象Post;你可以这样检查:

trash = moesearch.search(...)
print(type(trash))
print(trash)

for i, j in enumerate(trash):
    print(type(j))
    ...

推荐阅读