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

Python调用LinkedIn API动态设置dateRange end值返回500错误问题问询

问题修复方案

错误原因

  • 字符串未正确格式化:你使用普通单引号包裹请求URL,Python不会解析占位符{epochcdt},导致实际传给接口的end参数是字符串{epochcdt}而非你生成的时间戳数值,接口无法解析异常参数返回500错误
  • 时间戳格式不符合要求:datetime.now().timestamp()*1000生成的是浮点型数值,LinkedIn API要求传入毫秒级整数时间戳
  • 变量命名冲突:函数名organization_info和返回值接收变量重名,容易引发作用域异常
  • 代码块位置错误:文件写入、结果打印逻辑放在if __name__ == '__main__'外,非直接运行脚本时会触发未定义变量错误

修复步骤

  1. 给URL字符串添加f前缀,启用f-string格式化,让变量epochcdt正确代入URL
  2. 给时间戳添加int()转换,生成符合要求的整数类型毫秒时间戳
  3. 修正冲突的变量命名,调整代码块位置
  4. 推荐用requests的params参数传递查询字段,规避手动拼接URL的编码风险

修复后完整代码

import requests
import json
 
from liapiauth import auth, headers
from datetime import datetime

# 生成毫秒级整数时间戳
epochcdt = int(datetime.now().timestamp() * 1000)

def get_organization_info(headers):
    base_url = 'https://api.linkedin.com/v2/organizationalEntityShareStatistics'
    # 用params参数传递查询字段,更规范不易出错
    params = {
        'q': 'organizationalEntity',
        'organizationalEntity': 'urn:li:organization:XXXXX',
        'timeIntervals': f'(timeRange:(start:1596206929000,end:{epochcdt}),timeGranularityType:DAY)'
    }
    response = requests.get(base_url, params=params, headers=headers)
    org_info = response.json()
    return org_info
 
if __name__ == '__main__':
    credentials = 'credentials.json'
    access_token = auth(credentials)
    req_headers = headers(access_token)
    org_share_stats = get_organization_info(req_headers)

    with open('lishare14m.json', 'w') as outfile:
        json.dump(org_share_stats, outfile)

    print(org_share_stats)

内容的提问来源于stack exchange,提问作者Piotr Chmurzynski

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 14:36:03