python - 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 个请求。其他端点不受限制。
解决方案
在第 40 行moesearch
转换为 JSON的源代码是正确的,但再往下几行,您可以看到该函数返回一个对象列表(第 44 行,语句):search()
Post
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))
...
推荐阅读
- mysql - 如何在多列中显示mysql嵌套的json数据?
- c# - 在 Xamarin Android 中创建一个需要点击 3 次的按钮
- php - 只允许 zip 文件上传
- mysql - 如何在jsp页面的本地文件夹中获取上传的文件?
- java - 使用 Bytebuddy 动态创建类和方法
- python - pandas:如何获取 NaT 的当前日期时间
- spring-boot - 带有 cassandra 的 Spring 数据给出 IllegalStateException
- angular - angular-tree-component 的“treeNodeFullTemplate”的使用不清楚
- sharepoint - 如何从 windowsidentity 上下文切换到代表 sharepoint windowsclaims 用户的上下文
- c++ - 如何使用 libnetconf2 的 nc_recv_reply 获取回复数据