如何用Python requests库替换API地址占位符并获取用户输入?
Python中结合用户输入调用翻译API的实现方法
核心步骤说明
- 通过
input()函数获取用户输入的API令牌和待翻译文本 - 固定设置
action为google、lang为fa(波斯语) - 替换API URL占位符时,推荐使用
requests的params参数,它会自动处理URL编码,避免特殊字符引发的问题
具体实现代码
方法一:直接字符串格式化(f-string)
这种方式简单直观,但需注意待翻译文本含特殊字符时可能出现编码问题:
import requests # 获取用户输入 token = input("输入你的API令牌: ") query = input("输入要翻译的文本: ") action = "google" lang = "fa" # 替换占位符并发送请求 api_url = f"https://one-api.ir/translate/?token={token}&action={action}&lang={lang}&q={query}" response = requests.get(api_url) # 解析并输出结果 try: print("翻译结果:", response.json()['result']) except KeyError: print("API返回错误,响应内容:", response.json())
方法二:使用requests的params参数(推荐)
该方式会自动处理URL编码,适配含空格、特殊符号的待翻译文本,稳定性更强:
import requests # 获取用户输入 token = input("输入你的API令牌: ") query = input("输入要翻译的文本: ") # 定义请求参数字典 params = { 'token': token, 'action': 'google', 'lang': 'fa', 'q': query } # 发送请求,requests自动拼接参数到URL response = requests.get("https://one-api.ir/translate/", params=params) # 解析并输出结果 try: print("翻译结果:", response.json()['result']) except KeyError: print("API返回错误,响应内容:", response.json())
增强版:完善异常处理
添加网络异常、HTTP状态码异常、JSON解析异常的捕获,提升代码健壮性:
import requests try: # 获取用户输入 token = input("输入你的API令牌: ") query = input("输入要翻译的文本: ") params = { 'token': token, 'action': 'google', 'lang': 'fa', 'q': query } # 发送请求并检查HTTP状态 response = requests.get("https://one-api.ir/translate/", params=params) response.raise_for_status() # 解析响应 response_data = response.json() if 'result' in response_data: print("翻译结果:", response_data['result']) else: print("API未返回翻译结果,响应内容:", response_data) except requests.exceptions.RequestException as e: print("请求过程出错:", str(e)) except ValueError: print("API返回的响应不是合法JSON格式")
内容的提问来源于stack exchange,提问作者Sepehr
相关产品推荐
相关产品推荐

