Python爬虫:如何筛选字典列表中符合条件的录音条目并提取指定键值对
解决方案
你可以通过列表推导式或for循环对获取到的recordings列表进行筛选和字段提取,以下是具体实现:
方法1:列表推导式(简洁高效)
在原有代码基础上添加筛选逻辑:
import requests url = "https://xeno-canto.org/api/2/recordings?query=emberiza+pusilla" response = requests.get(url) json_data = response.json() recordings = json_data['recordings'] # 筛选类型为song的条目,提取指定键值对 filtered_recordings = [ { '录制国家': item['cnt'], '录音ID': item['id'], '音频链接': item['file'] } for item in recordings # 用get避免无type字段的条目抛出KeyError if item.get('type') == 'song' ] # 打印前3条结果示例 for rec in filtered_recordings[:3]: print(rec)
方法2:for循环(直观易读)
如果对列表推导式不熟悉,也可以用普通循环实现:
import requests url = "https://xeno-canto.org/api/2/recordings?query=emberiza+pusilla" response = requests.get(url) json_data = response.json() recordings = json_data['recordings'] filtered_recordings = [] for item in recordings: # 检查录音类型是否为song if item.get('type') == 'song': # 提取需要的字段,忽略其他无关键值对 cleaned_item = { '录制国家': item['cnt'], '录音ID': item['id'], '音频链接': item['file'] } filtered_recordings.append(cleaned_item)
关键说明
- 使用
item.get('type')而非直接item['type'],是为了避免部分条目缺失type字段时触发KeyError; - 你可以根据需求调整提取的字段,比如添加
录制日期: item['date']等; - 如果部分条目缺失
cnt(国家)字段,同样可以用item.get('cnt', '未知国家')设置默认值,避免报错。
内容的提问来源于stack exchange,提问作者whorrodwi
相关产品推荐
相关产品推荐

