Python中的Feedparser和多线程
我有一个将近500个的RSS/ATOM源网址的列表,想要解析并获取其中的链接。
我正在使用Python的feedparser库来解析这些网址。为了同时处理这些网址,我想到了使用Python的线程库。
我的代码大概是这样的:
import threading
import feedparser
class PullFeeds:
def _init__(self):
self.data = open('urls.txt', 'r')
def pullfeed(self):
threads = []
for url in self.data:
t = RssParser(url)
threads.append(t)
for thread in threads:
thread.start()
for thread in threads:
thread.join()
class RssParser(threading.Thread):
def __init__(self, url):
threading.Thread.__init__(self)
self.url = url
def run(self):
print "Starting: ", self.name
rss_data = feedparser.parse(self.url)
for entry in rss_data.get('entries'):
print entry.get('link')
print "Exiting: ", self.name
pf = PullFeeds()
pf.pullfeed()
问题是,当我运行这个脚本时,Feedparser返回了一个空列表。但是如果不使用线程,feedparser就能正常打印出从提供的网址解析出来的链接。
我该怎么解决这个问题呢?
2 个回答
1
为了检查问题是否出在多线程上,你可以尝试使用多个进程来代替:
#!/usr/bin/env python
####from multiprocessing.dummy import Pool # use threads
from multiprocessing import Pool # use processes
from multiprocessing import freeze_support
import feedparser
def fetch_rss(url):
try:
data = feedparser.parse(url)
except Exception as e:
return url, None, str(e)
else:
e = data.get('bozo_exception')
return url, data['entries'], str(e) if e else None
if __name__=="__main__":
freeze_support()
with open('urls.txt') as file:
urls = (line.strip() for line in file if line.strip())
pool = Pool(20) # no more than 20 concurrent downloads
for url, items, error in pool.imap_unordered(fetch_rss, urls):
if error is None:
print(url, len(items))
else:
print(url, error)
0
问题出在Vagrant上。我是在我的一个Vagrant虚拟机里运行这个脚本的,而同样的脚本在Vagrant外面运行得很好。
这个问题需要被报告。我还不确定应该把这个bug报告到哪里,是Vagrant的问题,还是Python的线程问题,或者是Feedparser库的问题。