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

Python处理JSON缺失字段:无domain时追加指定内容至列表

Python处理Scale SERP API返回数据中缺失的domain字段

下面是完整的实现脚本,包含API请求、数据保存以及缺失字段的处理逻辑:

import requests
import json

# 替换为你的Scale SERP API密钥和搜索关键词
API_KEY = "your_api_key_here"
SEARCH_QUERY = "your_competitor_keyword"
API_URL = f"https://api.scaleserp.com/search?api_key={API_KEY}&q={SEARCH_QUERY}"

# 发送GET请求并获取响应
response = requests.get(API_URL)
response.raise_for_status()  # 捕获请求错误

# 将返回数据保存为JSON文件
with open('serp_results.json', 'w', encoding='utf-8') as f:
    json.dump(response.json(), f, indent=2, ensure_ascii=False)

# 初始化存储列表
sRanks = []
sTitles = []
sDomains = []

# 解析JSON数据并提取字段
serp_data = response.json()
for idx, result in enumerate(serp_data.get('organic_results', []), start=1):
    # 提取排名(优先用API返回的position字段,无则用循环索引)
    sRanks.append(result.get('position', idx))
    # 提取标题,无则填充默认值
    sTitles.append(result.get('title', 'no title'))
    # 处理domain字段缺失:存在则取对应值,否则填充'no domain'
    domain = result.get('domain', 'no domain')
    sDomains.append(domain)

# 验证结果
print("排名列表:", sRanks)
print("标题列表:", sTitles)
print("域名列表:", sDomains)

关键逻辑说明

  • 用requests.get()发起API请求,response.raise_for_status()能在请求失败时直接抛出异常,避免后续无效的数据处理。
  • 通过json.dump()将响应数据写入本地文件,方便后续核对原始数据。
  • 遍历organic_results时,使用字典的get()方法处理字段缺失:该方法会在目标字段不存在时返回指定的默认值,比传统的if-else判断更简洁高效。

内容的提问来源于stack exchange,提问作者Vinicius Stanula

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:10:28