rss没有立即更新

2024-09-25 06:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个小脚本,专门监视RSS上的“用python标记的新问题”。它在循环的第一次迭代中将提要存储在变量中,然后根据变量中存储的提要不断检查提要。如果feed发生变化,它将更新变量并将最新的条目输出到控制台,并播放一个声音文件,提醒我有新的问题。总而言之,这是相当方便的,因为我不必盯着任何东西。然而,在实际发布的新问题和我的脚本检测feed更新之间存在时间差异。这些差异似乎在时间上有所不同,但一般来说,它不是即时的,而且往往不会在对问题采取足够的行动之前提醒我,因此它几乎已经得到了处理。不总是这样,但一般来说。我是否有办法确保更快或更快的更新/警报?或者这是最好的吗?(我突然想到,这个特定的提要只有在对某个问题有实际操作时才会更新。。有人知道是不是真的吗?)在

我是否误解了rss的实际工作方式?在

import urllib2
import mp3play
import time
from xml.dom import minidom



def SO_notify():
    """ play alarm when rss is updated """

rss = ''
filename = "path_to_soundfile"
mp3 = mp3play.load(filename)
mp3.volume(25)

while True:  
    html = urllib2.urlopen("http://stackoverflow.com/feeds/tag?tagnames=python&sort=newest")
    new_rss = html.read()
    if new_rss == rss:
        continue
    rss = new_rss
    feed = minidom.parseString(rss)
    new_entry = feed.getElementsByTagName('entry')[0]
    title = new_entry.getElementsByTagName('title')[0].childNodes[0].nodeValue
    print title
    mp3.play()
    time.sleep(30) #Edit - thanks to all who suggested this

SO_notify()

Tags: import脚本newsotimetitlefeed时间
2条回答

IMHO,根据您想要的方法,您可以有两种解决方案:

  1. 使用JSON-这将为您提供一个包含所有条目的漂亮dict。在
  2. 使用RSS(XML)。在本例中,您需要类似于feedparser的内容来处理XML。在

无论哪种方式,代码都应该类似于:

    # make curr_ids a dictionary for easier lookup
    curr_ids = []

    filename = "path_to_soundfile"
    mp3 = mp3play.load(filename)
    mp3.volume(25)

    # Loop
    while True:
        # Get the list of entries in objects
        entries = get_list_of_entries()

        new_ids = []

        for entry in entries:
            # Check if we reached the most recent entry
            if entry.id in curr_ids:
                # Force loop end if we did
                break

            new_ids.append(entry.id)

            # Do whatever operations
            print entry.title

        if len(new_ids) > 0:
           mp3.play()
           curr_ids = new_ids
        else:
           # No updates in the meantime
           pass

        sleep(30)

注意事项:

  • 我用“oldest”来排序条目,这样打印出来的条目看起来就像一个流,最近的条目是最后打印出来的条目。在
  • new_ids的事情是将id列表保持在最小值。否则查找会随着时间的推移而变慢
  • get_list_of_entries()是一个容器,用于从源获取条目(对象来自XML或dict来自JSON)。根据您想要的方法,引用它们是不同的(但原理是相同的)

比如:

import requests
import mp3play
import time

curr_ids = []
filename = "path_to_soundfile"
mp3 = mp3play.load(filename)
mp3.volume(25)

while True:
    api_json = requests.get("http://api.stackoverflow.com/1.1/questions/unanswered?order=desc&tagged=python").json()
    new_questions = []
    all_questions = []
    for q in api_json["questions"]:
        all_questions.append(q["question_id"])
        if q["question_id"] not in curr_ids:
            new_questions.append(q["question_id"])
    if new_questions:
        print(new_questions)
        mp3.play()
    curr_ids = all_questions
    time.sleep(30)

在这里使用了requests包,因为urllib给了我一些编码问题。在

相关问题 更多 >