我使用Scrapy获取网站信息,然后将信息写入JSON文件。
用Scrapy本身启动它可以正常工作,但是当我用Scrapyd启动它时,我发现JSON文件不是在同一个路径中创建的。
import math
from typing import Any
import scrapy
from scrapy.http import Response
import json
from scrapy.utils.conf import closest_scrapy_cfg
import os
def __init__(self, start_urls=None, *args, **kwargs):
super(NsidcInfoSpider, self).__init__(*args, **kwargs)
# XPath namespaces
self.namespaces = {
...
}
# get the store dir
proj_root = closest_scrapy_cfg()
if proj_root:
proj_root = os.path.dirname(proj_root)
proj_root = proj_root + "\\files\\info"
if not os.path.exists(proj_root):
os.makedirs(proj_root)
self.file = open(proj_root + '\\entries.json', 'a')
def parse(self, response):
# get the website information and parse it to obj
obj = {}
json_string = json.dumps(obj)
self.file.write(json_string + '\n')
def closed(self, reason):
self.file.close()
Scrapy中的closest_scrapy_cfg()函数用于定位最近的scrapy.cfg配置文件。因此,当我使用 scrapyd 调度蜘蛛时,JSON 文件不会写入 scrapy 项目目录中。
为了解决此问题,我选择使用 FILES_STORE 设置编写 JSON 文件,从而允许我指定文件的绝对路径。
settings = get_project_settings()
file_store = settings.get('FILES_STORE')
if file_store:
file_store = os.path.dirname(file_store)
file_store = file_store + "\\nsidc\\info"
if not os.path.exists(file_store):
os.makedirs(file_store)
self.file = open(file_store + '\\entries.json', 'a')