我是Python的新手,需要一些帮助。
我有一个脚本:
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)
打印的响应是:
{"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
,则必须启动以下脚本:
import requests
url = "https://www.example2.com/api/v2/report?apikey=XXXXXXXXXXXXXXX&data=runData"
r = requests.get(url, verify=False)
print(r.status_code)
仅此而已(
p.S.请使用尽可能少的模块,因为我的系统(使用Phython(可能不支持它们
感谢所有人!
因此,就像评论中提到的gold_cy一样,您可以将响应内容转换为JSON,而不是将数据解析为文本,这将允许您访问类似于典型词典的信息。
所以你可以很容易地做到这一点:
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...