scrapy开发几个注意点

一、开发工具pycharm使用debugger功能

scrapy开发过程中需要开启debugger调试模式配置如下:

  • 1、在根目录下才创建一个main.py的文件
  • 2、在里面书写的代码内容

    from scrapy.cmdline import execute
    import sys
    import os
    
    
    # 将当前文件添加到path路径下
    
    sys.path.append(os.path.dirname(os.path.abspath(__file__)))
    
    
    # 开启哪个爬虫
    
    execute(['scrapy', 'crawl', 'cnblog'])
  • 3、直接运行main.py文件就可以

二、在抓取数据的时候调试

  • 1、使用shell

    scrapy shell 需要抓取网页的url地址
  • 2、在黑窗口写代码调试

三、自定义命令

  • 1、在spider的同级目录下创建一个包,包名称commands
  • 2、里面创建一个你要运行的命令的文件夹crawlall.py
  • 3、书写代码

    from scrapy.commands import ScrapyCommand
    
    
    class Command(ScrapyCommand):
        requires_project = True
    
        def syntax(self):
            return '[options]'
    
        def short_desc(self):
            return 'runs all of the spiders'
    
        def run(self, args, opts):
            spider_list = self.crawler_process.spiders.list()
            for name in spider_list:
                self.crawler_process.crawl(name, **opts.__dict__)
            self.crawler_process.start()
    
  • 4、在settings.py中配置

    
    # 配置
    
    COMMANDS_MODULE = 'scrapy_demo01.commands'
  • 5、查看命令

    scrapy --help
    
    # 运行项目下全部的爬虫
    
    scrapy crawlall

四、解决项目中乱码的问题

  • settings.py中配置

    FEED_EXPORT_ENCODING = 'utf-8'

猜你喜欢

转载自blog.csdn.net/kuangshp128/article/details/80039064