如何在没有json的情况下在python中获取apis输出

时间:2021-01-21 19:30:12

标签: python discord discord.py discord.py-rewrite

这是我正在尝试的 api https://api.apithis.net/host2ip.php?hostname=google.com 正如您所看到的,与 json apis 不同,它没有“”,您可以将其复制为 response.json

@client.command()
async def host(ctx, host):
    url = ('https://api.apithis.net/host2ip.php?hostname=' + host)

    response = requests.get(url)
    ipaddress = response.json()

    embed = discord.Embed(title="IP for website" + host, color=0x00ffff)
    embed.add_field(name="IP:", value=f'{ipaddress}', inline=True)                                                            
    
    await ctx.send(embed=embed)

这是我当前的代码,如果有人可以修复会很有帮助,因为我不确定如何在没有 json 输出的情况下使用 api,谢谢

2 个答案:

答案 0 :(得分:1)

您可以简单地使用 Response.text 属性

reponse = requests.get(url).text # e.g 0.0.0.0

答案 1 :(得分:0)

首先,您得到的响应不是 JSON。如果你看到 response header 那么你可以看到它是 content-type: text/html; charset=UTF-8

既然它不是 JSON,您必须将其视为文本。

r = requests.get(url)
ipaddress = r.text if r.status_code == 200 else ''
相关问题