【问题标题】:TypeError: 'Post' object is not subscriptableTypeError:“发布”对象不可下标
【发布时间】:2019-08-30 21:54:06
【问题描述】:

目前试图弄清楚为什么我不能从返回的字典中提取特定的键/值。查看这个问题,我发现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

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

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

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

    【讨论】:

    • 知道了,所以遍历 Post() 对象基本上就像遍历字典列表一样?
    • @SebastianGoslin 我不确定;您将不得不阅读Post class 的定义
    猜你喜欢
    • 2016-07-20
    • 1970-01-01
    • 2017-07-15
    • 2021-10-01
    • 2019-12-07
    • 2012-01-09
    • 2021-11-23
    • 2012-02-21
    • 2018-08-07
    相关资源
    最近更新 更多