【问题标题】:Some questions about using multiple piplines in scrapy关于在scrapy中使用多个管道的一些问题
【发布时间】:2020-09-07 13:39:10
【问题描述】:

我是scrapy的新手,几天前我开始了一个简单的项目。我已经成功地实现了items.pymy_spider.pypiplines.py 将一些信息 到一个json 文件中。现在我想给我的蜘蛛添加一些功能,遇到了一些问题。

我已经在论坛的线程中抓取了所需的信息,包括file_urlsimage_urls。我对Scrapy Documentation 的教程有点困惑,以下是我文件中的相关部分:

**settings.py**
...
ITEM_PIPELINES = {
    'my_project.pipelines.InfoPipeline': 300,
    'scrapy.pipelines.images.ImagesPipeline': 300,
    'scrapy.pipelines.files.FilesPipeline': 300,
}
FILES_STORE = './Downloads'
IMAGES_STORE = './Downloads'
**items.py**
...
class InfoIterm(scrapy.Item):
    movie_number_title = scrapy.Field()
    movie_pics_links = scrapy.Field()
    magnet_link = scrapy.Field()
    torrent_link = scrapy.Field()
    torrent_name = scrapy.Field()


class TorrentItem(scrapy.Item):
    file_urls = scrapy.Field()
    files = scrapy.Field()


class ImageItem(scrapy.Item):
    image_urls = scrapy.Field()
    images = scrapy.Field()
**piplines.py**
...
def process_item(self, item, spider):
    contents = json.dumps(dict(item), indent=4, sort_keys=True, ensure_ascii=False)
    with open("./threads_data.json", "wb") as f:
        f.write(contents.encode("utf-8"))
    return item
**my_spider.py**
...
def parse_thread(self, response):
    json_item = InfoIterm()
    json_item['movie_number_title'] = response.xpath("//span[@id='thread_subject']/text()").getall()
    json_item['movie_pics_links'] = response.xpath("//td[@class='t_f']//img/@file").getall()
    json_item['magnet_link'] = response.xpath("//div[@class='blockcode']/div//li/text()").getall()
    json_item['torrent_name'] = response.xpath("//p[@class='attnm']/a/text()").getall()
    json_item['torrent_link'] = self.base_url + response.xpath("//p[@class='attnm']/a/@href").getall()[0]
    yield json_item

    torrent_link = self.base_url + response.xpath("//p[@class='attnm']/a/@href").getall()
    yield {'file_urls': torrent_link}

    movie_pics_links = response.xpath("//td[@class='t_f']//img/@file").getall()
    yield {'image_urls': movie_pics_links}

现在我可以成功下载图像,但文件没有下载。我的 json 文件也被最后一个 image_urls 覆盖。

所以,这是我的问题:

  1. 一个蜘蛛可以使用多个管道吗?如果可能,使用它们的最佳方式是什么(例如,就我而言。一些例子会很棒!)?
  2. 在某些情况下,其中一些json_item['xxx'] 不会出现在某些线程上,并且控制台将打印一些报告问题的信息。我尝试在代码的每一行上使用try-except,但它变得非常丑陋,我相信应该有更好的方法来做到这一点。最好的方法是什么?

非常感谢。

【问题讨论】:

    标签: scrapy scrapy-pipeline


    【解决方案1】:

    1- 是的,您可以使用多个管道,但您需要注意它们的调用顺序。 (更多关于here

    如果它们旨在处理不同的 Item 对象,您需要做的就是检查在 process_item 方法中接收到的项目的类。处理你想要的,让其他的原封不动。

    2- 错误是什么,如果没有这些信息,将无济于事。请发布执行日志。

    【讨论】:

      猜你喜欢
      • 2013-12-05
      • 2020-02-02
      • 1970-01-01
      • 1970-01-01
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 2018-06-03
      相关资源
      最近更新 更多