如何使用Python从请求响应中过滤所需数据

2024-06-09 22:50:46 发布

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

我有一些get请求的响应存储在变量中,如下所示。。。在

dashboard = 'http://12.345.67.890:8000/api/search?query=&starred=false'
dashboardr = s.get(dashboard)
dashboards = dashboardr.content
print(dashboards)

回复如下。。。在

^{pr2}$

有人能帮我把title的值提取出来并存储在另一个变量中吗?在

上述回复中的标题值为

Apple
Banana
Mango

Tags: apifalsehttp标题searchgettitlecontent
3条回答

假设HTTP调用的响应是一个字符串,下面的代码将提取标题。在

import json

response_str = '[{"id": 19, "title": "Apple", "uri": "db/abc-api", "type": "dash-db", "tags": [], "isStarred": false},{"id": 20, "title": "Banana", "uri": "db/cde-api", "type": "dash-db", "tags": [], "isStarred": false},{"id": 7, "title": "Mango", "uri": "db/efg", "type": "dash-db", "tags": [], "isStarred": false}]'
response_dict = json.loads(response_str)
titles = [entry['title'] for entry in response_dict]
print(titles)

输出:

^{pr2}$
for i in eval(dashboards.replace('false', 'False')):
    print(i['title'])

不用打印标题,您可以将其保存在列表变量中。在

使用eval(仪表板)而不是仪表板。在

dashboard = 'http://12.345.67.890:8000/api/search?query=&starred=false'
dashboardr = s.get(dashboard)
# eval() will convert a string to a python statement/expression
dashboards = eval(dashboardr.content)

title_list = []
for _ in dashboards:
   title_list.append(dashboards["title"])

相关问题 更多 >