首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >解析Python response.text

解析Python response.text
EN

Stack Overflow用户
提问于 2020-10-13 23:00:55
回答 1查看 114关注 0票数 0

我是Python的新手,我需要一点帮助。

我有个剧本:

代码语言:javascript
复制
import requests
url = "https://www.example.com/vtapi/v2/ip-address/report?apikey=XXXXXXXXXXXXXXX&ip=8.8.8.8"
r = requests.get(url, verify=False)
print(r.text)

印制的答复是:

代码语言:javascript
复制
{"asn": 45899, "undetected_urls": [], "undetected_downloaded_samples": [{"date": "2019-07-25 00:55:11", "positives": 0, "total": 70, "sha256": "FDFEFDSFgrgd"}], "country": "VN", "response_code": 1, "as_owner": "VNPT Corp", "verbose_msg": "IP address in dataset", "detected_downloaded_samples": [{"date": "2020-10-13 06:47:34", "positives": 35, "total": 74, "sha256": "dfghdfghdfghdfgh"}], "detected_urls": [{"url": "http://8.8.8.8/", "positives": 3, "total": 79, "scan_date": "2020-10-13 21:27:33"}, {"url": "https://8.8.8.8/", "positives": 3, "total": 79, "scan_date": "2020-10-13 16:10:11"}, {"url": "http://8.8.8.8:49594/Mozi.m", "positives": 2, "total": 79, "scan_date": "2020-10-13 15:47:47"}, {"url": "http://8.8.8.8:49594/Mozi.m/", "positives": 1, "total": 79, "scan_date": "2020-10-13 15:43:04"}], "resolutions": []}

所以,我需要解析的数据,从"detected_urls":开始,包含[{"url": "http://8.8.8.8/", "positives": 3, "total": 79, "scan_date": "2020-10-13 21:27:33"}{"url": "https://8.8.8.8/", "positives": 3, "total": 79, "scan_date": "2020-10-13 16:10:11"}....etc....... --可能是1,2,3-10-20块,但是我需要只使用(注意)第一个块,比如[{"url": "http://8.8.8.8/", "positives": 3, "total": 79, "scan_date": "2020-10-13 21:27:33"},并解析"positives": 3数据。

然后,

如果响应中没有"detected_urls":子句,那么必须有print "Session closed"

如果"positives"计数大于0,那么必须启动以下脚本:

代码语言:javascript
复制
import requests
url = "https://www.example2.com/api/v2/report?apikey=XXXXXXXXXXXXXXX&data=runData"
r = requests.get(url, verify=False)
print(r.status_code)

))

请使用尽可能少的模块,因为我的系统(使用Phython)可能不支持它们!

感谢大家!

EN

回答 1

Stack Overflow用户

发布于 2020-10-13 23:16:44

因此,就像注释中提到的gold_cy一样,您可以将响应内容转换为JSON,而不是将数据解析为文本,这将允许您访问类似于典型字典的信息。

这样您就可以很容易地做到如下所示:

代码语言:javascript
复制
response = requests.get(url, verify=False)
res_json = response.json()

if len(res_json['detected_urls']) == 0:
    # Do stuff
    ...
else:
    # Get the first item from detected_urls
    first = res_json['detected_urls'][0]
    # Do stuff...
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64344307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档