You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 01:46:19