【发布时间】:2020-09-07 13:39:10
【问题描述】:
我是scrapy的新手,几天前我开始了一个简单的项目。我已经成功地实现了items.py、my_spider.py 和piplines.py 将一些信息刮 到一个json 文件中。现在我想给我的蜘蛛添加一些功能,遇到了一些问题。
我已经在论坛的线程中抓取了所需的信息,包括file_urls 和image_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 覆盖。
所以,这是我的问题:
- 一个蜘蛛可以使用多个管道吗?如果可能,使用它们的最佳方式是什么(例如,就我而言。一些例子会很棒!)?
- 在某些情况下,其中一些
json_item['xxx']不会出现在某些线程上,并且控制台将打印一些报告问题的信息。我尝试在代码的每一行上使用try-except,但它变得非常丑陋,我相信应该有更好的方法来做到这一点。最好的方法是什么?
非常感谢。
【问题讨论】: