scrapy在pipelines中获取项目根目录
项目结构

方法一
python
import os
class MyPipeline:
def process_item(self, item, spider):
# 获取当前目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 向上移动到项目根目录
project_root = os.path.abspath(os.path.join(current_dir, os.pardir))
# 现在你可以使用project_root来访问项目根目录的文件
print("项目根目录:", project_root)
return item
方法二
python
import os
class MyPipeline:
def process_item(self, item, spider):
# 获取当前工作目录
current_dir = os.path.dirname(os.path.abspath(__file__))
# 向上移动到项目根目录
project_root = os.path.dirname(current_dir)
# 现在你可以使用project_root来访问项目根目录的文件
print("项目根目录:", project_root)
return item
方法三
python
import os
class MyPipeline:
def process_item(self, item, spider):
# 获取项目目录
project_dir = os.getcwd()
# 现在你可以使用project_root来访问项目根目录的文件
print("项目根目录:", project_root)
return item