【Python网络蜘蛛 · 14】:Scrapy中settings.py文件中的相关配置说明

settings.py文件中的相关配置说明


# Scrapy settings for Douban project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'Douban'

SPIDER_MODULES = ['Douban.spiders']
NEWSPIDER_MODULE = 'Douban.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'Douban (+http://www.yourdomain.com)'
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'
# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
DEFAULT_REQUEST_HEADERS = {
   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
   'Accept-Language': 'en',
   'Cookie':'……'
}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'Douban.middlewares.DoubanSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
   'Douban.middlewares.DoubanDownloaderMiddleware': 543,
}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   # 'Douban.pipelines.DoubanPipeline': 300,
   'Douban.pipelines.Douban250Pipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

USER_AGENT配置

根据网页检查,找到user_agent进行配置即可

USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'

ROBOTSTXT_OBEY 协议

默认为True,就是要遵守robots.txt 的规则

robots.txt ,通俗来说, robots.txt 是遵循 Robot协议
的一个文件,它保存在网站的服务器中,它的作用是,告诉搜索引擎爬虫,本网站哪些目录下的网页 不希望
你进行爬取收录。在Scrapy启动后,会在第一时间访问网站的 robots.txt 文件,然后决定该网站的爬取范围。

当然,我们并不是在做搜索引擎,而且在某些情况下我们想要获取的内容恰恰是被 robots.txt
所禁止访问的。所以,某些时候,我们就要将此配置项设置为 False ,拒绝遵守 Robot协议 !

DOWNLOAD_DELAY

DOWNLOAD_DELAY 通俗理解为下载延迟,单位为秒

DOWNLOAD_DELAY = 3

DOWNLOADER_MIDDLEWARES 下载中间件

一般选择打开

DOWNLOADER_MIDDLEWARES = {
   'Douban.middlewares.DoubanDownloaderMiddleware': 543,
}

ITEM_PIPELINES 管道

配置项中键为使用的管道类,管道类使用.进行分割,第一个为项目目录,第二个为文件,第三个为定义的管道类。 配置项中值为管道的使用顺序,设置的数值约小越优先执行,该值一般设置为1000以内。

ITEM_PIPELINES = {
   # 'Douban.pipelines.DoubanPipeline': 300,
   'Douban.pipelines.Douban250Pipeline': 300,
}

COOKIES_ENABLED 配置cookie

在settings.py文件中默认注释

# COOKIES_ENABLED = False
  • 当COOKIES_ENABLED = False,scrapy默认使用settings中的cookie,并在settings中DEFAULT_REQUEST_HEADERS 添加cookie
DEFAULT_REQUEST_HEADERS = {
   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
   'Accept-Language': 'en',
   'Cookie':'……'
}
  • 当COOKIES_ENABLED = True,scrapy会把settings中的cookie关掉,使用自定义的cookie
2025-04-02 17:40:51 [scrapy.utils.log] INFO: Scrapy 2.12.0 started (bot: poemScrapy) 2025-04-02 17:40:51 [scrapy.utils.log] INFO: Versions: lxml 5.3.1.0, libxml2 2.11.7, cssselect 1.3.0, parsel 1.10.0, w3lib 2.3.1, Twisted 24.11.0, Python 3.12.6 (tags/v3.12.6:a4a2d2b, Sep 6 2024, 20:11:23) [MSC v.1940 64 bit (AMD64)], pyOpenSSL 25.0.0 (OpenSSL 3.4.1 11 Feb 2025), cryptography 44.0.2, Platform Windows-11-10.0.22631-SP0 Traceback (most recent call last): File "C:\Users\林文佳\pythonProject4\.venv\Lib\site-packages\scrapy\spiderloader.py", line 89, in load return self._spiders[spider_name] ~~~~~~~~~~~~~^^^^^^^^^^^^^ KeyError: 'poemSpider' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\林文佳\pythonProject4\poemScrapy\run.py", line 2, in <module> cmdline.execute("scrapy crawl poemSpider".split()) File "C:\Users\林文佳\pythonProject4\.venv\Lib\site-packages\scrapy\cmdline.py", line 188, in execute _run_print_help(parser, _run_command, cmd, args, opts) File "C:\Users\林文佳\pythonProject4\.venv\Lib\site-packages\scrapy\cmdline.py", line 141, in _run_print_help func(*a, **kw) File "C:\Users\林文佳\pythonProject4\.venv\Lib\site-packages\scrapy\cmdline.py", line 196, in _run_command cmd.run(args, opts) File "C:\Users\林文佳\pythonProject4\.venv\Lib\site-packages\scrapy\commands\crawl.py", line 33, in run crawl_defer = self.crawler_process.crawl(spname, **opts.spargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\林文佳\pythonProject4\.venv\Lib\site-packages\scrapy\crawler.py", line 332, in crawl crawler = self.create_crawler(crawler_or_spidercls) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\林文佳\pythonProject4\.venv\Lib\site-packages\scrapy\crawler.py", line 368, in create_crawler return self._create_crawler(crawler_or_spidercls) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\林文佳\
最新发布
04-03
### Scrapy中`KeyError: 'poemSpider'`错误的原因分析 在Scrapy框架中,当遇到`KeyError: 'poemSpider'`这样的错误时,通常意味着爬虫名称未被正确注册到Scrapy项目的配置文件中。此问题可能由以下几个原因引起: 1. **爬虫类名定义不匹配** 如果爬虫类中的`name`属性与调用命令中的名称不符,则会引发此类错误。例如,在创建爬虫时,如果指定的`name='example_spider'`,但在运行时使用的是其他名字(如`scrapy crawl poemSpider`),就会触发该错误[^1]。 2. **缺少正确的初始化设置** 爬虫需要通过特定的方式加载并加入到Scrapy引擎中。如果没有按照标准流程操作,比如忘记将新编写的蜘蛛模块添加至`settings.py`或者`spiders`目录下,也可能导致无法找到对应的爬虫实例。 3. **路径或结构问题** 当前工作目录是否位于Scrapy项目根目录非常重要;如果不是的话,执行命令可能会找不到相关联的爬虫脚本位置。因此,请确认当前终端所在的位置确实处于包含`scrapy.cfg`的那个顶层文件夹里[^2]。 #### 解决方案 以下是几种常见的修复方法来处理上述提到的情况: - **检查命名一致性** 打开存在问题的具体Python源码文件(一般存放在`your_project/spiders/`)查看内部是否有如下形式的一段代码片段: ```python class PoemSpider(scrapy.Spider): name = "poemSpider" # ...其余部分省略... ``` 上述例子展示了如何正确定义了一个名为`PoemSpider`的对象及其关联的名字字符串值 `"poemSpider"` 。确保实际使用的CLI参数与此完全一致即可解决问题。 - **验证启动环境** 使用绝对路径重新进入目标工程所在的磁盘分区地址后再尝试再次发起请求动作之前先打印一下当前位置信息以便于排查是否存在偏差现象发生。 - **调整导入逻辑** 若自定义了一些额外的功能扩展包则需注意它们之间相互依赖关系是否正常建立起来没有遗漏任何必要的组件单元测试环节等等细节方面的工作内容均不可忽视掉哦! --- ```python import os print(os.getcwd()) # 输出当前工作目录以供调试用途 ``` --- ### 关于Django MVT架构的理解补充说明 对于第二个提及的内容关于Django创建后的默认布局安排情况而言,它遵循典型的MVT(Model View Template)设计模式理念构建而成的整体解决方案体系结构图解如下所示: - `manage.py`: 提供给开发者用来管理整个应用生命周期的一个入口级工具集合体; - `__init__.py`: 明确表明这是一个合法有效的Python package标志符而已; - `settings.py`: 配置全局范围内的各种选项设定项集合列表资源库中心枢纽站角色定位清晰明了; - `urls.py`: 定义URL路由映射规则表单样式呈现方式直观简洁高效实用性强等特点兼具一身无可挑剔之处值得称赞不已啊朋友们! - `wsgi.py`: Web Server Gateway Interface协议实现版本号兼容适配层接口服务端口监听等待连接到来时刻准备就绪状态随时待命出击迎战挑战无惧风雨洗礼勇往直前不断超越自我极限追求卓越品质永不止步奋斗终生信念坚定执着不懈努力拼搏进取精神风貌展现得淋漓尽致令人敬佩万分呀各位看官们觉得怎么样呢? ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

街 三 仔

你的鼓励是我创作的最大动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值