首页 > 解决方案 > 无法在scrapy爬虫中导入我自己的模块

问题描述

我正在使用 Scrapy 编写爬虫。我已经建立了一个爬虫,它工作得很好。

现在我想创建自己的模块,但我总是收到这个错误:

文件“D:\Projects\bitbucket\terranoha\crawl1\crawl1\spiders\samplecrawler.py”,第 4 行,在导入模块测试中

ModuleNotFoundError:没有名为“moduletest”的模块

代码是:

from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
import moduletest

class SamplecrawlerSpider(CrawlSpider):
    # [...]

我在跑: scrapy crawl --nolog samplecrawler。我在 Windows 10 上。

我的项目结构是:

在此处输入图像描述

标签: pythonscrapy

解决方案


你可以做几件事:

第一的

from crawl1.spiders.moduletest import mythings

正如@elRuLL 所建议的那样

第二

from .moduletest import mythings

这通常是一个糟糕而脆弱的解决方案,但可能。

第三

您可以将其打包为包并执行。

初始化.py:

from spiders.moduletest import *
__all__ = [<Put your classes, methods, etc here>]

样本爬虫.py

import moduletest

推荐阅读