Python循环从列表取值创建URL遇类型错误,如何生成6个唯一URL?
解决TypeError: can only concatenate str (not "list") to str问题
错误根源
你在循环里犯了个低级错误:用整个report列表和字符串拼接,而不是用循环变量x。Python不允许字符串和列表直接拼接,所以直接抛出了类型错误。
修正后的代码
import datetime import requests # 确保你的token已经正确赋值 acces_token = "your_actual_token" today = str(datetime.date.today()) start = str(datetime.date.today() - datetime.timedelta(days=30)) report = [ "Shifts", "ShiftStops", "ShiftStopDetailsByProcessDate", "TimeRegistrations", "ShiftsByProcessDate", "ShiftStopsByProcessDate", ] for x in report: # 用循环变量x替换原来的report列表,同时用f-string让拼接更清爽 url_data = f"https://URL{x}?from={start}&until={today}" response = requests.get( url_data, headers={ 'Host': 'services.URL.com', 'Authorization': f'Bearer {acces_token}' } ) # 可以打印生成的URL验证正确性 print(f"生成的URL: {url_data}") # 也可以检查请求状态码 print(f"请求状态码: {response.status_code}")
核心改动
- 把字符串拼接里的
report换成循环变量x,每次循环取列表里的一个报表名称,生成唯一的URL。 - 用f-string替代传统的
+拼接,代码更易读,也减少拼接错误。 - 补上
datetime和requests的导入语句,确保脚本能正常运行。
修改后,循环会生成6个对应不同报表的唯一URL,并分别发起GET请求。
内容的提问来源于stack exchange,提问作者Catscanner
相关产品推荐
相关产品推荐

