【问题标题】:Python Feedparser and Multi-threadingPython Feedparser 和多线程
【发布时间】:2014-04-18 16:11:13
【问题描述】:

我有一个 RSS/ATOM 提要 URL 列表(近 500 个)来解析和获取链接。

我正在使用 python feedparser 库来解析 url。为了并行解析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 解析的链接列表。

我该如何解决这个问题?

【问题讨论】:

    标签: python multithreading feedparser


    【解决方案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)
    

    【讨论】:

    • 我会尽快回复您。感谢您的帮助。
    【解决方案2】:

    问题在于 Vagrant。我在我的一台流浪机器中运行脚本。相同的脚本在 vagrant box 中运行良好。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多