繁体   English   中英

Python Feedparser和多线程

[英]Python Feedparser and Multi-threading

我有一个RSS / ATOM供稿网址列表(将近500个),用于解析和获取链接。

我正在使用python feedparser libary解析URL。 为了并行解析网址列表,我想到了在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会打印出从提供的URL解析的链接列表。

我该如何解决?

若要查看问题是否与多线程有关,您可以尝试使用多个进程来代替:

#!/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)

问题出在流浪汉。 我在一台无业游民的机器中运行脚本。 相同的脚本可以在“无家可归”框中正常运行。

这需要报告。 我不确定在哪里报告此错误,无论是Vagrant还是Python线程或Feedparser库有问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM