TypeError:“Post”对象不是subscriptab

2024-06-26 09:55:05 发布

您现在位置:Python中文网/ 问答频道 /正文

目前正在试图找出为什么我不能从返回的dict中提取特定的键/值。查找这个问题时,我发现this earlier问题基本上是这样的:为了被访问,对象需要采用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

我尝试在请求通过trash = dict(trash)完成后将其显式转换为dict,但返回另一个错误:

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

以前有人碰到过这个吗?这段代码是可执行的,请记住搜索API每分钟被限制为5个请求。其他的终点并不受限制。你知道吗


Tags: 对象inimportjsontimestampcommentexport
1条回答
网友
1楼 · 发布于 2024-06-26 09:55:05

moesearch的源代码在Line 40中转换为JSON是正确的,但是在下面几行您可以看到函数search()返回了Post对象的列表(line 44,即return语句):

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))
    ...

相关问题 更多 >