Python爬虫 --- 2.4 Scrapy之天气预报爬虫实践

原文链接:https://www.fkomm.cn/article/2018/8/5/31.html

目的

写一个真正意义上一个爬虫,并将他爬取到的数据分别保存到txt、json、已经存在的mysql数据库中。

目标分析:

这次我们要爬的是 中国天气网:http://www.weather.com.cn/ 。随便点开一个城市的天气比如合肥: http://www.weather.com.cn/weather/101220101.shtml 。我们要爬取的就是图中的:合肥七天的前期预报:

pic1

数据的筛选:

我们使用chrome开发者工具,模拟鼠标定位到相对应位置:

pic2

可以看到我们需要的数据,全都包裹在

<ul class="t clearfix">

里。 我们用bs4、xpath、css之类的选择器定位到这里,再筛选数据就行。 本着学习新知识的原则,文中的代码将会使用xpath定位。 这里我们可以这样:

response.xpath('//ul[@class="t clearfix"]')

Scrapy 框架的实施:

创建scrapy项目和爬虫:

    $ scrapy startproject weather
     $ cd weather
     $ scrapy genspider HFtianqi www.weather.com.cn/weather/101220101.shtml

这样我们就已经将准备工作做完了。 看一下当前的目录:

     ├── scrapy.cfg
     └── weather
         ├── __init__.py
         ├── __pycache__
         │   ├── __init__.cpython-36.pyc
         │   └── settings.cpython-36.pyc
         ├── items.py
         ├── middlewares.py
         ├── pipelines.py
         ├── settings.py
         └── spiders
             ├── HFtianqi.py
             ├── __init__.py
             └── __pycache__
                 └── __init__.cpython-36.pyc

     4 directories, 11 files

编写items.py:

这次我们来先编写items,十分的简单,只需要将希望获取的字段名填写进去:

    import scrapy

     class WeatherItem(scrapy.Item):
         # define the fields for your item here like:
         # name = scrapy.Field()
         date = scrapy.Field()
         temperature = scrapy.Field()
         weather = scrapy.Field()
         wind = scrapy.Field()

编写Spider:

这个部分使我们整个爬虫的核心!!

主要目的是:

将Downloader发给我们的Response里筛选数据,并返回给PIPELINE处理。

下面我们来看一下代码:

    # -*- coding: utf-8 -*-
     import scrapy

     from weather.items import WeatherItem

     class HftianqiSpider(scrapy.Spider):
         name = 'HFtianqi'
         allowed_domains = ['www.weather.com.cn/weather/101220101.shtml']
         start_urls = ['http://www.weather.com.cn/weather/101220101.shtml']

         def parse(self, response):
             '''
             筛选信息的函数:
             date = 日期
             temperature = 当天的温度
             weather = 当天的天气
             wind = 当天的风向
             '''

             # 先建立一个列表,用来保存每天的信息
             items = []

             # 找到包裹着天气信息的div
             day = response.xpath('//ul[@class="t clearfix"]')

             # 循环筛选出每天的信息:
             for i  in list(range(7)):
                 # 先申请一个weatheritem 的类型来保存结果
                 item = WeatherItem()

                 # 观察网页,并找到需要的数据
                 item['date'] = day.xpath('./li['+ str(i+1) + ']/h1//text()').extract()[0]

                 item['temperature'] = day.xpath('./li['+ str(i+1) + ']/p[@class="tem"]/i/text()').extract()[0]

                 item['weather'] = day.xpath('./li['+ str(i+1) + ']/p[@class="wea"]/text()').extract()[0]

                 item['wind'] = day.xpath('./li['+ str(i+1) + ']/p[@class="win"]/em/span/@title').extract()[0] + day.xpath('./li['+ str(i+1) + ']/p[@class="win"]/i/text()').extract()[0]

                 items.append(item)

             return items

编写PIPELINE:

我们知道,pipelines.py是用来处理收尾爬虫抓到的数据的, 一般情况下,我们会将数据存到本地:

  • 文本形式: 最基本的存储方式
  • json格式 :方便调用
  • 数据库: 数据量比较大时选择的存储方式

TXT(文本)格式:

        import os
        import requests
        import json
        import codecs
        import pymysql

        class WeatherPipeline(object):
          def process_item(self, item, spider):

              print(item)
              # print(item)
              # 获取当前工作目录
              base_dir = os.getcwd()
              # 文件存在data目录下的weather.txt文件内,data目录和txt文件需要自己事先建立好
              filename = base_dir + '/data/weather.txt'

              # 从内存以追加的方式打开文件,并写入对应的数据
              with open(filename, 'a') as f:
                  f.write(item['date'] + '\n')
                  f.write(item['temperature'] + '\n')
                  f.write(item['weather'] + '\n')
                  f.write(item['wind'] + '\n\n')

              return item

json格式数据:

我们想要输出json格式的数据,最方便的是在PIPELINE里自定义一个class:

        class W2json(object):
          def process_item(self, item, spider):
              '''
              讲爬取的信息保存到json
              方便其他程序员调用
              '''
              base_dir = os.getcwd()
              filename = base_dir + '/data/weather.json'

              # 打开json文件,向里面以dumps的方式吸入数据
              # 注意需要有一个参数ensure_ascii=False ,不然数据会直接为utf编码的方式存入比如:“/xe15”
              with codecs.open(filename, 'a') as f:
                  line = json.dumps(dict(item), ensure_ascii=False) + '\n'
                  f.write(line)

              return item

数据库格式(mysql):

Python对市面上各种各样的数据库的操作都有良好的支持, 但是现在一般比较常用的免费数据库mysql。

  • 在本地安装mysql:

linux和mac都有很强大的包管理软件,如apt,brew等等,window 可以直接去官网下载安装包。

由于我是Mac,所以我是说Mac的安装方式了。

$ brew install mysql

在安装的过程中,他会要求你填写root用户的密码,这里的root并不是系统层面上的超级用户,是mysql数据库的超级用户。 安装完成后mysql服务是默认启动的, 如果重启了电脑,需要这样启动(mac):

$ mysql.server start

  • 登录mysql并创建scrapy用的数据库:
 # 登录进mysql
  $ mysql -uroot -p

  # 创建数据库:ScrapyDB ,以utf8位编码格式,每条语句以’;‘结尾
  CREATE DATABASE ScrapyDB CHARACTER SET 'utf8';

  # 选中刚才创建的表:
  use ScrapyDB;

  # 创建我们需要的字段:字段要和我们代码里一一对应,方便我们一会写sql语句
  CREATE TABLE weather(
  id INT AUTO_INCREMENT,
  date char(24),
  temperature char(24),
  weather char(24),
  wind char(24),
  PRIMARY KEY(id) )ENGINE=InnoDB DEFAULT CHARSET='utf8'

来看一下weather表长啥样:

show columns from weather
或者:desc weather
  • 安装Python的mysql模块:

pip install pymysql

最后我们编辑一下代码:

class W2mysql(object):
      def process_item(self, item, spider):
          '''
          将爬取的信息保存到mysql
          '''

          # 将item里的数据拿出来
          date = item['date']
          temperature = item['temperature']
          weather = item['weather']
          wind = item['wind']

          # 和本地的scrapyDB数据库建立连接
          connection = pymysql.connect(
              host='127.0.0.1',  # 连接的是本地数据库
              user='root',        # 自己的mysql用户名
              passwd='********',  # 自己的密码
              db='ScrapyDB',      # 数据库的名字
              charset='utf8mb4',     # 默认的编码方式:
              cursorclass=pymysql.cursors.DictCursor)

          try:
              with connection.cursor() as cursor:
                  # 创建更新值的sql语句
                  sql = """INSERT INTO WEATHER(date,temperature,weather,wind)
                          VALUES (%s, %s, %s, %s)"""
                  # 执行sql语句
                  # excute 的第二个参数可以将sql缺省语句补全,一般以元组的格式
                  cursor.execute(
                      sql, (date, temperature, weather, wind))

              # 提交本次插入的记录
              connection.commit()
          finally:
              # 关闭连接
              connection.close()

  return item

编写Settings.py

我们需要在Settings.py将我们写好的PIPELINE添加进去, scrapy才能够跑起来。

这里只需要增加一个dict格式的ITEM_PIPELINES, 数字value可以自定义,数字越小的优先处理。

    BOT_NAME = 'weather'

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

     ROBOTSTXT_OBEY = True

     ITEM_PIPELINES = {
        'weather.pipelines.WeatherPipeline': 300,
        'weather.pipelines.W2json': 400,
        'weather.pipelines.W2mysql': 300,
     }

让项目跑起来:

$ scrapy crawl HFtianqi

结果展示:

文本格式:
pic3

json格式:
pic4

数据库格式:
pic5

这次的例子就到这里了,主要介绍如何通过自定义PIPELINE来将爬取的数据以不同的方式保存。


相关文章和视频推荐

圆方圆学院汇集 Python + AI 名师,打造精品的 Python + AI 技术课程。 在各大平台都长期有优质免费公开课,欢迎报名收看。

公开课地址:https://ke.qq.com/course/362788?flowToken=1007321

加入python学习讨论群 78486745 ,获取资料,和广大群友一起学习。
圆方圆python技术讨论群

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值