python - 使用 scrapy 创建 RSS

标签 python rss scrapy pipeline

我添加了一个管道,我在 stackoverflow 中找到了一个示例项目的答案。 它是:

import csv
from craiglist_sample import settings


def write_to_csv(item):
   writer = csv.writer(open(settings.csv_file_path, 'a'), lineterminator='\n')
    writer.writerow([item[key] for key in item.keys()])



class WriteToCsv(object):
    def process_item(self, item, spider):
        write_to_csv(item)
        return item

它可以正确写入 csv 文件。然后我将其更改为这个:

import csv
import sys
from craiglist_sample import settings
import datetime
import PyRSS2Gen

def write_to_csv(item):

    rss = PyRSS2Gen.RSS2(
        title = "Andrew's PyRSS2Gen feed",
        link = "http://www.dalkescientific.com/Python/PyRSS2Gen.html",
        description = "The latest news about PyRSS2Gen, a "
                      "Python library for generating RSS2 feeds",

        lastBuildDate = datetime.datetime.now(),

        items = [
           PyRSS2Gen.RSSItem(
             title =str((item['title']),
             link = str((item['link']),
             description = "Dalke Scientific today announced PyRSS2Gen-0.0, "
                           "a library for generating RSS feeds for Python.  ",
             guid = PyRSS2Gen.Guid("http://www.dalkescientific.com/news/"
                              "030906-PyRSS2Gen.html"),
             pubDate = datetime.datetime(2003, 9, 6, 21, 31)),

        ])

    rss.write_xml(open("pyrss2gen.xml", "w"))

class WriteToCsv(object):
    def process_item(self, item, spider):
        write_to_csv(item)
        return item

但问题是它只将最后一个条目写入 xml 文件。我怎样才能解决这个问题?我需要为每个条目添加新行吗?

items.py 是:

class CraiglistSampleItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title=Field()
    link=Field()

最佳答案

使用a追加,每次使用w都会覆盖,所以你只能得到最后一条数据:

rss.write_xml(open("pyrss2gen.xml", "a"))

如果您查看原始代码,您会发现它也使用 a 而不是 w

您可能想使用with打开文件或至少关闭它们时。

关于python - 使用 scrapy 创建 RSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28127396/

相关文章:

python - Scrapy 将 URL 标题保存在文本文件中

python - 具有多个文件字段的django表单

python - Jsonify 自定义对象列表

用于读取 RSS 和 ATOM 提要的 java 库

php - 如何通过命令行在服务器上运行php脚本

python - 使用 scrapy-splash 选择依赖下拉菜单

python - 从 ubuntu 上的 google app engine 开始

python - Setup.py 安装需要本地包

jquery - 使用 jQuery 读取 RSS 提要?

python - 将 Scrapy 指向本地缓存而不是执行正常的爬取过程