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

使用Python从PubChem获取1176.784±0.01Da分子时请求报错400

问题分析与解决

错误原因

请求返回400是因为URL格式不符合PubChem API要求:原代码中用%f+-%0.3f拼接的范围字符串,会在URL中生成类似1176.784000 -0.005的格式(+在URL中被解析为空格),PubChem无法识别这种格式的质量范围查询。

修正后的代码

import requests

exact_mass = 1176.784  # 目标精确质量
tolerance = 0.01       # 总容差

# 计算质量范围的上下限
mass_low = exact_mass - tolerance / 2
mass_high = exact_mass + tolerance / 2

# 构造正确的API请求URL:用逗号分隔上下限
url = f"https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/list/exactmass/{mass_low:.3f},{mass_high:.3f}/property/IUPACName/JSON"

response = requests.get(url)

if response.ok:
    json_data = response.json()
    # 直接从PropertyTable中提取所有IUPAC名称,无需逐个请求CID
    properties = json_data.get("PropertyTable", {}).get("Properties", [])
    for prop in properties:
        iupac_name = prop.get("IUPACName")
        if iupac_name:
            print(iupac_name)
else:
    print(f'Error: 请求失败,状态码 {response.status_code}')
    # 打印响应内容,方便排查具体错误
    print(response.text)

关键修改点

  • URL格式修正:用逗号分隔质量上下限(low,high),这是PubChem API认可的范围查询格式
  • 减少请求次数:原代码先获取CID列表再逐个请求名称,修正后直接一次性获取所有符合条件的分子的IUPAC名称,提升效率
  • 增加容错处理:用get()方法访问JSON字段,避免因字段缺失导致报错;打印响应内容便于排查API返回的具体错误信息

内容的提问来源于stack exchange,提问作者John Mommers

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 02:05:22