原文连接:https://www.fkomm.cn/article/...css
写一个真正意义上一个爬虫,并将他爬取到的数据分别保存到txt、json、已经存在的mysql数据库中。html
此次咱们要爬的是 中国天气网:http://www.weather.com.cn/ 。随便点开一个城市的天气好比合肥: http://www.weather.com.cn/wea... 。咱们要爬取的就是图中的:合肥七天的前期预报:python
数据的筛选:mysql
咱们使用chrome开发者工具,模拟鼠标定位到相对应位置:linux
能够看到咱们须要的数据,全都包裹在程序员
<ul class="t clearfix">
sql
里。 咱们用bs四、xpath、css之类的选择器定位到这里,再筛选数据就行。 本着学习新知识的原则,文中的代码将会使用xpath定位。 这里咱们能够这样:chrome
response.xpath('//ul[@class="t clearfix"]')
数据库
$ scrapy startproject weather $ cd weather $ scrapy genspider HFtianqi www.weather.com.cn/weather/101220101.shtml
这样咱们就已经将准备工做作完了。 看一下当前的目录:json
├── 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,十分的简单,只须要将但愿获取的字段名填写进去:
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()
这个部分使咱们整个爬虫的核心!!
主要目的是:
将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
咱们知道,pipelines.py是用来处理收尾爬虫抓到的数据的, 通常状况下,咱们会将数据存到本地:
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。
linux和mac都有很强大的包管理软件,如apt,brew等等,window 能够直接去官网下载安装包。
因为我是Mac,因此我是说Mac的安装方式了。
$ brew install mysql
在安装的过程当中,他会要求你填写root用户的密码,这里的root并非系统层面上的超级用户,是mysql数据库的超级用户。 安装完成后mysql服务是默认启动的, 若是重启了电脑,须要这样启动(mac):
$ mysql.server start
# 登陆进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
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将咱们写好的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
文本格式:
json格式:
数据库格式:
此次的例子就到这里了,主要介绍如何经过自定义PIPELINE来将爬取的数据以不一样的方式保存。
圆方圆学院聚集 Python + AI 名师,打造精品的 Python + AI 技术课程。 在各大平台都长期有优质免费公开课,欢迎报名收看。
公开课地址:https://ke.qq.com/course/362788