• Scrapy框架的安装
    • pip install pywin32
    • 下载 Twisted 包       pip install Twisted包的路径
    • pip insatll scrapy
  • Scrapy的基本使用
    • 切换到开始项目的目录
    • scrapy startproject my_first_spider 命令创建一个新项目
    • scrapy genspider my_first_spider www.xxx.com
    • 目录结构如下
    • # -*- coding: utf-8 -*-
      import scrapy
      from my_first_spider.items import MyFirstSpiderItem class FirstSpider(scrapy.Spider):
      # 当前spider的名称
      name = 'first' # 允许的域名
      # allowed_domains = ['www.xxx.com'] # 开始的第一个url
      start_urls = ['https://www.zhipin.com/c101010100/?query=python开发&page=1&ka=page-1'] url = 'https://www.zhipin.com/c101010100/?query=python开发&page=%d&ka=page-1'
      page = 1 # 用于解析的解析函数, 适用 xpath, 必传参数response
      def parse(self, response):
      div_list = response.xpath('//div[@class="job-list"]/ul/li')
      for div in div_list:
      job = div.xpath('./div/div[1]/h3/a/div[1]/text()').extract_first()
      salary = div.xpath('./div/div[1]/h3/a/span/text()').extract_first()
      company = div.xpath('./div/div[2]/div/h3/a/text()').extract_first() item = MyFirstSpiderItem() item['job'] = job
      item['salary'] = salary
      item['company'] = company yield item # 将item对象返回给数据持久化管道(pipelines) # 分页爬取
      if self.page <= 7:
      print(f'第{self.page}页爬取完毕,开始爬取第{self.page+1}页')
      self.page += 1
      yield scrapy.Request(url=self.url%self.page, callback=self.parse)

      first.py

    • # -*- coding: utf-8 -*-
      
      # Define here the models for your scraped items
      #
      # See documentation in:
      # https://doc.scrapy.org/en/latest/topics/items.html import scrapy # 与管道交互,实例化item对象进行交互,将爬取到的数据封装在对象中,以对象的方式进行文件间数据传递
      class MyFirstSpiderItem(scrapy.Item):
      # define the fields for your item here like:
      # name = scrapy.Field()
      job = scrapy.Field()
      salary = scrapy.Field()
      company = scrapy.Field()

      item.py

    • # -*- coding: utf-8 -*-
      
      # Define your item pipelines here
      #
      # Don't forget to add your pipeline to the ITEM_PIPELINES setting
      # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import redis # 写入boss.txt文件
      class MyFirstSpiderPipeline(object): fp = None def open_spider(self, spider):
      print('开始爬虫')
      self.fp = open('./boss.txt', 'w', encoding='utf8') def close_spider(self, spider):
      self.fp.close()
      print('爬虫结束') def process_item(self, item, spider): self.fp.write(item['job']+':'+item['salary']+':'+item['company']+'\n') return item # MySQL 写入管道
      class MySqlPipeline(object):
      conn = None
      cursor = None # 爬虫开始后如若使用管道, 首先执行open_spider方法(打开mysql数据库连接)
      def open_spider(self, spider): import pymysql.cursors self.conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', password='root',
      db='scrapy', charset='utf8')
      # print('-----', self.conn)
      print('打开MySQL连接, 开始写入') # 第二步 执行process_item 函数, 在其中进行写入操作, 如若有在此管道之后还有管道 此方法要将item对象返回
      def process_item(self, item, spider): self.cursor = self.conn.cursor()
      try:
      self.cursor.execute(
      'INSERT INTO boss (job_name, salary, company) VALUES ("%s", "%s", "%s")' % (item['job'], item['salary'], item['company']))
      self.conn.commit()
      except Exception as e:
      self.conn.rollback()
      print('出现错误, 事件回滚')
      print(e) # 第三部爬虫结束后执行close_spider方法(关闭MySQL连接)
      def close_spider(self, spider): self.conn.close()
      self.cursor.close()
      print('MySQl 写入完毕') # Redis 写入管道
      class RedisPipeline(object): conn = None def open_spider(self, spider):
      self.conn = redis.Redis(host='127.0.0.1', port=6379) # 第二步 执行process_item 函数, 在其中进行写入操作, 如若有在此管道之后还有管道 此方法要将item对象返回
      def process_item(self, item, spider):
      import json
      dic = {
      'job_name': item['job'],
      'salary': item['salary'],
      'company': item['company']
      }
      try:
      self.conn.lpush('boss', json.dumps(dic))
      print('redis 写入成功')
      except Exception as e: print('redis 写入失败', e)
      return item

      pipeline.py

    • # Configure item pipelines
      # See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
      ITEM_PIPELINES = {
      'my_first_spider.pipelines.MyFirstSpiderPipeline': 300,
      'my_first_spider.pipelines.RedisPipeline': 301,
      'my_first_spider.pipelines.MySqlPipeline': 302,
      } BOT_NAME = 'my_first_spider' SPIDER_MODULES = ['my_first_spider.spiders']
      NEWSPIDER_MODULE = 'my_first_spider.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent
      USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36' # Obey robots.txt rules
      ROBOTSTXT_OBEY = False

      setting.py

    • 在命令行中输入 scrapy crawl first --nolog  --nolog不显示日志
    • 爬取成功

Scrapy框架的使用的更多相关文章

  1. Python爬虫Scrapy框架入门(2)

    本文是跟着大神博客,尝试从网站上爬一堆东西,一堆你懂得的东西 附上原创链接: http://www.cnblogs.com/qiyeboy/p/5428240.html 基本思路是,查看网页元素,填写 ...

  2. Python爬虫Scrapy框架入门(1)

    也许是很少接触python的原因,我觉得是Scrapy框架和以往Java框架很不一样:它真的是个框架. 从表层来看,与Java框架引入jar包.配置xml或.property文件不同,Scrapy的模 ...

  3. Scrapy框架使用—quotesbot 项目(学习记录一)

    一.Scrapy框架的安装及相关理论知识的学习可以参考:http://www.yiibai.com/scrapy/scrapy_environment.html 二.重点记录我学习使用scrapy框架 ...

  4. Python爬虫从入门到放弃(十一)之 Scrapy框架整体的一个了解

    这里是通过爬取伯乐在线的全部文章为例子,让自己先对scrapy进行一个整理的理解 该例子中的详细代码会放到我的github地址:https://github.com/pythonsite/spider ...

  5. Python爬虫从入门到放弃(十二)之 Scrapy框架的架构和原理

    这一篇文章主要是为了对scrapy框架的工作流程以及各个组件功能的介绍 Scrapy目前已经可以很好的在python3上运行Scrapy使用了Twisted作为框架,Twisted有些特殊的地方是它是 ...

  6. python爬虫scrapy框架——人工识别登录知乎倒立文字验证码和数字英文验证码(2)

    操作环境:python3 在上一文中python爬虫scrapy框架--人工识别知乎登录知乎倒立文字验证码和数字英文验证码(1)我们已经介绍了用Requests库来登录知乎,本文如果看不懂可以先看之前 ...

  7. 一个scrapy框架的爬虫(爬取京东图书)

    我们的这个爬虫设计来爬取京东图书(jd.com). scrapy框架相信大家比较了解了.里面有很多复杂的机制,超出本文的范围. 1.爬虫spider tips: 1.xpath的语法比较坑,但是你可以 ...

  8. 安装scrapy框架的常见问题及其解决方法

    下面小编讲一下自己在windows10安装及配置Scrapy中遇到的一些坑及其解决的方法,现在总结如下,希望对大家有所帮助. 常见问题一:pip版本需要升级 如果你的pip版本比较老,可能在安装的过程 ...

  9. 关于使用scrapy框架编写爬虫以及Ajax动态加载问题、反爬问题解决方案

    Python爬虫总结 总的来说,Python爬虫所做的事情分为两个部分,1:将网页的内容全部抓取下来,2:对抓取到的内容和进行解析,得到我们需要的信息. 目前公认比较好用的爬虫框架为Scrapy,而且 ...

  10. 利用scrapy框架进行爬虫

    今天一个网友问爬虫知识,自己把许多小细节都忘了,很惭愧,所以这里写一下大概的步骤,主要是自己巩固一下知识,顺便复习一下.(scrapy框架有一个好处,就是可以爬取https的内容) [爬取的是杨子晚报 ...

随机推荐

  1. mysql 代价

    mysql cbo cost base optimizer 基于代价,数据是一直变化的oracle8 以前是rbo rule base optimizer 基于规则, 如果sql使用了索引,必须使用索 ...

  2. vue关闭令人抓狂的ESlint 语法检测配置方法

    随便改个vue 一堆报错 其实我并不反对这些语法检测,但是像许多反个人意愿的那就真的不得不吐槽了,比如vue-cli脚手架创建的默认eslint规则: 代码末尾不能加分号 ; 代码中不能存在多行空行 ...

  3. [转] maven打包可运行的fat-jar的简单方法

    [From] https://blog.csdn.net/tearsky253/article/details/75948721 问题 在使用“mvn package”命令编译application之 ...

  4. Django get_object ,get_queryset方法

    Django提供了很多通用的基于类的视图(Class Based View),可以帮我们简化执行以下操作的代码.这些基于类的视图还提供了get_queryset, get_context_data和g ...

  5. 下载Kitti 数据集(dataset) data_road.zip

    官网下载http://www.cvlibs.net/download.php?file=data_road.zip,耗时近3小时,虽然只有几百兆. 但是,我坚持下来了. 保存到了百度网盘,以供国内用户 ...

  6. Git创建版本库和添加文件

    创建版本库: 首先新建一个目录,然后通过 $ git init命令把这个目录变成Git可管理的仓库,例如: 在"C:\AmyPersonal\AmyGit"路径下新建文件夹Git1 ...

  7. Ubuntu下的RabbitMQ安装与web管理配置

    首先在Ubutnu的/etc/apt/sources.list文件中加入一行 deb http://cz.archive.ubuntu.com/ubuntu trusty main 然后执行 sudo ...

  8. LinuxShell脚本编程基础5--数值,字符串,文件状态测试,((..))和[[..]]的使用

    1.数值比较 ! /bin/bash echo "enter a score:" read num1 ] then echo "Very Good" elif ...

  9. [目录]ASP.NET web api开发实战

    第一章:Restful web service v.s. RPC style web service 第二章:ASP.NET web api v.s. WCF v.s. ASP.NET web ser ...

  10. clearfix的用法

    如果有一个DIV作为外部容器,内部的DIV如果设置了float样式,则外部的容器DIV因为内部没有 clear,导致不能被撑开.看下面的例子:Div布局如下:Css代码如下:.out{border:1 ...