使用feedparser解析时如何获取所有podcast:person重复标签的列表
问题原因
feedparser默认处理RSS扩展标签时,重复出现的同名字段会直接覆盖前值,仅保留最后一条,所以你当前只能拿到最后一个host的信息。
解决方法
两种常用方案可选:
方案1:修改feedparser解析规则,全局支持多podcast:person返回
主动给feedparser注册podcast命名空间,同时标记podcast:person为多值字段,解析时自动聚合为列表:
import feedparser # 注册podcast标准命名空间 feedparser.registerNamespace('podcast', 'https://github.com/Podcastindex-org/podcast-namespace/blob/main/docs/1.0.md') # 标记podcast:person为多值字段,参数1代表允许多次出现,返回列表 if ('podcast:person', 1) not in feedparser._FeedParserMixin.rss20_elements: feedparser._FeedParserMixin.rss20_elements.append(('podcast:person', 1)) # 正常解析订阅源 d = feedparser.parse('https://feeds.podcastmirror.com/dudesanddadspodcast') # 此时d.feed['podcast_person']就是包含所有条目的列表 print(d.feed['podcast_person'])
方案2:直接解析原始XML(兼容性更强,无需修改feedparser全局配置)
如果不想改动feedparser的全局规则,可以直接拉取订阅源原始内容,用XML解析库手动提取所有person标签:
import requests from lxml import etree # 拉取原始订阅源内容 resp = requests.get('https://feeds.podcastmirror.com/dudesanddadspodcast') root = etree.fromstring(resp.content) # 注册podcast命名空间 ns = {'podcast': 'https://github.com/Podcastindex-org/podcast-namespace/blob/main/docs/1.0.md'} # 提取所有person标签 person_nodes = root.xpath('//channel/podcast:person', namespaces=ns) # 格式化所有person信息为字典列表 person_list = [] for node in person_nodes: info = dict(node.attrib) info['name'] = node.text.strip() person_list.append(info) print(person_list)
内容的提问来源于stack exchange,提问作者Brenden
相关产品推荐
相关产品推荐

