如何在Python中将输入的ID嵌入URL?解决JSON解码报错问题
问题原因及解决方法
你的问题出在没有将变量id的值实际嵌入到URL中——原来的代码里,URL字符串中的'id'只是普通文本,并非引用变量,导致请求的是无效地址https://fantasy.premierleague.com/api/entry/'id'/history/,返回的内容自然不是合法JSON,所以触发了解码错误。
以下是几种简便的实现方式:
1. 使用f-string(Python 3.6+推荐)
这是最简洁直观的写法:
id = input("Enter your ID here: ") manager_history_url = f"https://fantasy.premierleague.com/api/entry/{id}/history/"
2. 使用str.format()方法
兼容性更好,适合Python 3.5及以下版本:
id = input("Enter your ID here: ") manager_history_url = "https://fantasy.premierleague.com/api/entry/{}/history/".format(id)
3. 字符串拼接(不推荐,但可用)
直接将变量与字符串片段拼接:
id = input("Enter your ID here: ") manager_history_url = "https://fantasy.premierleague.com/api/entry/" + id + "/history/"
上述方法都能正确把用户输入的ID替换到URL的对应位置,请求有效地址后就能获取合法的JSON数据了。
内容的提问来源于stack exchange,提问作者ILE2091
相关产品推荐
相关产品推荐

