简体   繁体   English

Python:在字典中列出?

[英]Python: List inside a Dict?

From this example, how do I get the IP address from the response?从这个示例中,我如何从响应中获取IP 地址

import requests

URL = "https://security.cloudflare-dns.com/dns-query?name=test.com"

session = requests.session()
r = session.get(URL, headers={"Accept": "application/dns-json"})
r = r.json()

print("Type:", type(r))
print("Len:", len(r))
print("Content:", r)

IP = r['Answer'][-1]
print("IP:", IP)  

Output: Output:

Type: <class 'dict'>
Len: 8
Content: {'Status': 0, 'TC': False, 'RD': True, 'RA': True, 'AD': False, 'CD': False, 'Question': [{'name': 'test.com', 'type': 1}], 'Answer': [{'name': 'test.com', 'type': 1, 'TTL': 3261, 'data': '69.172.200.235'}]}
IP: {'name': 'test.com', 'type': 1, 'TTL': 3261, 'data': '69.172.200.235'}

Like this?:像这样?:

IP = r['Answer'][-1]['data']
print("IP:", IP)

Output: Output:

IP: 69.172.200.235

The reply is:回复是:

r['Answer'][0]['data']

But I would like to give you a tip on how you could find this.但我想给你一个提示,告诉你如何找到这个。

I like to use the code module to run an interactive console inside my script:我喜欢使用代码模块在我的脚本中运行交互式控制台:

import requests
import code

URL = "https://security.cloudflare-dns.com/dns-query?name=test.com"

session = requests.session()
r = session.get(URL, headers={"Accept": "application/dns-json"})
r = r.json()

print("Type:", type(r))
print("Len:", len(r))
print("Content:", r)

code.interact(banner="after get request", locals=locals()) #interactive console is created here

IP = r['Answer'][-1]
print("IP:", IP)  

From there, you can play with local variables and test until you find what you need.从那里,您可以使用局部变量并进行测试,直到找到所需的内容。

I hope that will helps.我希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM