微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决无法在 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。