无法在 items.py 文件中导入模块 - Scrapy

问题描述

我是 Python 新手,目前正在学习使用蜘蛛抓取网页。按照教程,我坚持使用 Python 进行相对导入。

这是我当前文件夹的结构(由scrapy startproject p1提供):

folder structure

我的items.py文件

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


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

在我的 filetwo.py 中,它包含:

import scrapy
from p1.items import Test

当我运行代码时,我得到“ModuleNotFoundError: No module named 'p1'”

我也在网上看到一些人面临同样的问题,所以我尝试了 ..items import Test,但仍然没有奏效。它给了我错误ImportError: attempted relative import with no kNown parent package

有人能给我一盏灯吗?

提前致谢!

解决方法

不幸的是,您接受的答案是错误的。你不应该弄乱 sys.path。你应该:

$ cd P1
$ python -m p1.spiders.filetwo # note no .py

您显然是直接从蜘蛛包内部运行 filetwo.py 脚本 - 这是导致所有这些错误的 python 中的反模式。另一方面,弄乱 sys.path 会导致一系列细微的错误。

,

我相信我的评论应该对您有所帮助。但这里有一个例子

enter image description here

enter image description here

enter image description here