前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python爬虫 --- 2.4 Scrapy之天气预报爬虫实践

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

作者头像
緣來
发布2018-09-18 17:27:21
6100
发布2018-09-18 17:27:21
举报
文章被收录于专栏:緣來來來緣來來來

目的

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

目标分析:

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

数据的筛选:

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

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

代码语言:javascript
复制
<ul class="t clearfix">

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

代码语言:javascript
复制
response.xpath('//ul[@class="t clearfix"]')

Scrapy 框架的实施:

  1. 创建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
  2. 编写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()
  3. 编写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
  4. 编写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
  5. 编写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, }
  6. 让项目跑起来: $ scrapy crawl HFtianqi
  7. 结果展示: 文本格式:

json格式:

数据库格式:

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-08-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 目的
    • 目标分析:
      • 数据的筛选:
        • Scrapy 框架的实施:
        相关产品与服务
        云数据库 SQL Server
        腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档