Python XML Feed解析器无法找到特定事件

时间:2015-05-04 17:54:36

标签: python xml for-loop feedparser cap

我正在编写一个python脚本来读取NWS CAP警报,并查找龙卷风警告。我有足够的脚本来读取XML,但是当发出龙卷风警告时,我无法让它返回true。这是因为我的脚本只会读取XML中的一个事件。我现在已经让它读取了所有的XML但是如果有龙卷风警告则不会返回true,除非龙卷风警告是最后一个事件,因为它是如何循环的。任何人都可以在发出龙卷风警告的时候给我任何帮助,即使有其他警报,它会返回真的吗?

Count()

这是一个测试它的XML示例

import feedparser
import time

next_check = time.time()
tornado = False

while True:        

    if time.time() > next_check:
        url = 'http://127.0.0.1/test.xml'
        feed = feedparser.parse(url)

        for entry in feed.entries:
            if entry.has_key("cap_event") is False:
                tornado = False    
            else:
                if entry.cap_event == "Tornado Warning":
                    tornado = True    
            else:
                tornado = False


        print("Tornado: " + str(tornado))
        print("EVENT: " + entry.cap_event)
        next_check = time.time() + 5

1 个答案:

答案 0 :(得分:1)

If I understand you question correctly this should hopefully be a quick fix.

My understanding of the question is that you want the use the feedparser to check an xml file to see if it contains the following xml entry:

<cap:event>Tornado Warning</cap:event>

If it does anywhere in the document you want to have the variable tornado stored as True.

(You mention that you want to 'return' true but as you are not in a function, I speculated that you meant just change the variable to True)

Basically you just need to remove the else part of your statement. So it is like this:

(I removed 'if entry.has_key("cap_event") is False:' as I think it might be redundant as well)

import feedparser
import time

next_check = time.time()
#tornado = False 

while True:

    if time.time() > next_check:

        feed = feedparser.parse(r'/home/tomnl/test.xml')

        # if tornado is declared here it means the file is checked a fresh
        # each time
        tornado = False 

        for entry in feed.entries:

            if entry.cap_event == "Tornado Warning":
                tornado = True

            print("Tornado: " + str(tornado))
            print("EVENT: " + entry.cap_event)
            next_check = time.time() + 5

        print("FINAL tornado", tornado)

Hope it helps.