【问题标题】:I got a json.decoder.JSONDecodeError while requesting my IP请求我的 IP 时出现 json.decoder.JSONDecodeError
【发布时间】:2021-07-02 07:37:03
【问题描述】:
import requests

headers = {
    "Host" : "iplocation.com" 
}

res= requests.get("https://iplocation.com/", headers=headers).json()

print(res)

错误

json.decoder.JSONDecodeError:预期值:第 1 行第 1 列(字符 0)

我该怎么办?

【问题讨论】:

    标签: python json python-requests ip


    【解决方案1】:

    来自https://iplocation.com/ 的响应是 HTML 响应,而不是 JSON。此行将返回 HTML 文本响应:

    res = requests.get("https://iplocation.com/", headers=headers).text
    

    您可能正在寻找一个 JSON 端点来获取您的公共 IP 地址。像下面这样的东西应该可以工作:

    import requests
    
    res = requests.get("https://api.ipify.org?format=json").json()
    
    print(res['ip'])
    

    【讨论】:

    • 请使用"if res.status_code == codes["ok"]:"检查以确保状态码为200
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 2021-08-05
    • 2021-09-05
    • 2015-12-14
    • 1970-01-01
    • 2011-09-03
    相关资源
    最近更新 更多