Python调用LinkedIn API动态设置dateRange end值返回500错误问题问询
问题修复方案
错误原因
- 字符串未正确格式化:你使用普通单引号包裹请求URL,Python不会解析占位符
{epochcdt},导致实际传给接口的end参数是字符串{epochcdt}而非你生成的时间戳数值,接口无法解析异常参数返回500错误 - 时间戳格式不符合要求:
datetime.now().timestamp()*1000生成的是浮点型数值,LinkedIn API要求传入毫秒级整数时间戳 - 变量命名冲突:函数名
organization_info和返回值接收变量重名,容易引发作用域异常 - 代码块位置错误:文件写入、结果打印逻辑放在
if __name__ == '__main__'外,非直接运行脚本时会触发未定义变量错误
修复步骤
- 给URL字符串添加
f前缀,启用f-string格式化,让变量epochcdt正确代入URL - 给时间戳添加int()转换,生成符合要求的整数类型毫秒时间戳
- 修正冲突的变量命名,调整代码块位置
- 推荐用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
相关产品推荐
相关产品推荐

