如何在Python中处理requests.get返回的竖线分隔字符串?
处理竖线分隔字符串并批量构造API请求体
实现思路
全程在内存中处理数据,无需创建临时文件,完全适配cron定时运行需求:
- 用
requests拉取目标网站的竖线分隔字符串 - 拆分字符串为行,提取表头后将每行数据转换为字典
- 循环遍历字典,直接用字典作为请求体发送POST请求到目标API
完整代码
import requests # 替换为你的目标数据接口URL source_url = "https://example.com/data-source" # 替换为你的目标API接口URL target_api_url = "https://example.com/target-api" try: # 拉取源数据 response = requests.get(source_url) response.raise_for_status() # 捕获请求错误 raw_data = response.text except requests.exceptions.RequestException as e: print(f"拉取源数据失败:{str(e)}") exit(1) # 处理字符串,过滤空行并拆分每行 data_lines = [line.strip() for line in raw_data.split('\n') if line.strip()] if not data_lines: print("未获取到有效数据") exit(0) # 提取表头和数据行 header_fields = data_lines[0].split('|') data_rows = data_lines[1:] # 循环处理每一行数据 for row in data_rows: # 拆分每行的值 row_values = row.split('|') # 表头和值配对生成字典,直接作为请求体 request_body = dict(zip(header_fields, row_values)) try: # 发送POST请求到目标API api_response = requests.post(target_api_url, json=request_body) api_response.raise_for_status() print(f"成功提交数据:{request_body['name']}") except requests.exceptions.RequestException as e: print(f"提交数据失败 {request_body.get('name', '未知')}:{str(e)}")
关键细节说明
- 无文件操作:所有数据处理都在内存中完成,避免磁盘IO,适合定时任务场景
- 异常处理:添加了请求失败的捕获逻辑,确保单个数据行处理失败不影响整体循环
- 格式兼容:通过
dict(zip(header_fields, row_values))自动配对表头和数据,无需手动指定每个字段,扩展性更强
内容的提问来源于stack exchange,提问作者davepythonexample
相关产品推荐
相关产品推荐

