【问题标题】:Parsing <cap:event>, <cap:urgency> tags value using feedparser in python from a Atom/xml feed使用 python 中的 feedparser 从 Atom/xml 提要解析 <cap:event>、<cap:urgency> 标记值
【发布时间】:2023-03-28 06:00:01
【问题描述】:

我正在使用 feedparser 从 Atom/xml 提要文件中解析数据。该文件的链接是:

https://alerts.weather.gov/cap/oh.php?x=0

这是国家气象局发布的一个提要,用于提供天气警报信息。此提要使用通用警报协议 (CAP) 警报消息。我正在尝试解析以下内容:

<summary>...AIR QUALITY ADVISORY IN EFFECT UNTIL MIDNIGHT EDT TONIGHT... The Miami Valley Regional Planning Commission and the Regional Air Pollution Control Agency have issued an Air Pollution and Air Quality Advisory for Montgomery, Miami, Greene, Clark, Preble and Darke counties in the Miami Valley Region, until midnight EDT tonight.</summary>
<cap:event>Air Quality Alert</cap:event>
<cap:effective>2020-06-08T15:15:00-04:00</cap:effective>
<cap:expires>2020-06-09T19:30:00-04:00</cap:expires>
<cap:status>Actual</cap:status>
<cap:msgType>Alert</cap:msgType>
<cap:category>Met</cap:category>
<cap:urgency>Unknown</cap:urgency>
<cap:severity>Unknown</cap:severity>
<cap:certainty>Unknown</cap:certainty>
<cap:areaDesc>Clark; Darke; Greene; Miami; Montgomery; Preble</cap:areaDesc>

我可以解析出摘要,但我无法解析出标签,例如使用 feedparser。这就是我在 Raspberry Pi 项目中所需要的。我尝试了许多不同的方法,例如:

d = feedparser.parse('http://alerts.weather.gov/cap/ms.php?x=0')
print (d.entries[0].['cap_event'])
print (d.entries[0]['cap:event'])

当我尝试打印 (d.entries[0].['cap_event']) 时,出现以下错误:

%运行 feedparser2.py 文件“/home/n8mdp/MyPythonApps/feedparser2.py”,第 13 行 打印(d['entries'][0].['cap:event']) ^ SyntaxError: 无效语法

如果我使用 print (d.entries[0]['cap_event'],它会得到以下错误: 回溯(最近一次通话最后): 文件“/home/n8mdp/MyPythonApps/feedparser2.py”,第 13 行,在 打印(d['entries'][0]['cap:event']) getitem 中的文件“/home/n8mdp/.thonny/Python36/lib/python3.6/site-packages/feedparser.py”,第 356 行 return dict.getitem(self, key) KeyError: 'cap:event'

在 Ubuntu 18.04.4 LTS 中使用 Thonny 2.1.16。 Feedparser 已安装。

有人对我如何在 python 中使用 feedparser 解析这些标签有好的建议吗?

提前致谢!

【问题讨论】:

    标签: python-3.x feedparser thonny


    【解决方案1】:

    经过深入调查,我确定以下方法有效:

    print (alertFeed['entries'][nws_entry_id]['id'])
    print (alertFeed['entries'][nws_entry_id]['summary'])
    print (alertFeed['entries'][nws_entry_id]['cap_event'])
    print (alertFeed['entries'][nws_entry_id]['cap_urgency'])
    print (alertFeed['entries'][nws_entry_id]['cap_areadesc'])
    

    nws_entry_id 是提要中条目数的索引。必须实际审查 feedparser 返回的提要才能确定这一点。现在代码按预期运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多