我正在使用feedparser(Python)从多个网站获取一些RSS条目。
如何使用feedparser进行异步请求?我的意思是,我想获取一些RSS条目,但我不想等待响应。当我从feedparser请求获得响应时,应调用一个回调函数。在请求之后(可能在回复之前),我想进行一些计算。
谢谢大家,雨果
您可能最好从parsing到decouple fetching。 Feedparser是一个了不起的解析库,但是可能不是最好的HTTP客户端库。幸运的是,这很容易做到,因为Feedparser也可以parse a blob of text。
然后,这意味着您可以选择任何HTTP库进行轮询,只要它支持您的异步要求即可。您可能最终会使用Twisted及其WebClient之类的东西。
当然,另一种解决方案是避免自己进行所有昂贵的轮询,而是依靠像Superfeedr这样的解决方案,该解决方案将使用webhooks向您发送给定Feed中的新内容。
[2019更新
使用异步
import aiohttp
import asyncio
import async_timeout
import feedparser
import pprint
INTERVAL = 60
async def fetch(session, url):
with async_timeout.timeout(10):
async with session.get(url) as response:
return await response.text()
async def fetchfeeds(loop, feedurls, ircsock):
last_entry = None
feeds = []
for url in feedurls:
feeds.append({'url':url, 'last':""})
while True:
for feed in feeds:
async with aiohttp.ClientSession(loop=loop) as session:
html = await fetch(session, feed['url'])
rss = feedparser.parse(html)
if feed['last']:
if feed['last']['title'] != rss['entries'][0]['title'] and feed['last']['link'] != rss['entries'][0]['link']:
print("new entry")
feed['last'] = rss['entries'][0]
print("MSG {}".format(feed['last']['title']))
print("MSG {}".format(feed['last']['link']))
else:
feed['last'] = rss['entries'][0]
await asyncio.sleep(INTERVAL)
loop = asyncio.get_event_loop()
loop.run_until_complete(fetchfeeds(loop, ['https://n-o-d-e.net/rss/rss.xml',
"http://localhost:8000/rss.xml"], None))