爬取目标网站:

http://www.weather.com.cn/

具体区域天气地址:

http://www.weather.com.cn/weather1d/101280601.shtm(深圳)

开始:

scrapy startproject weather

编写items.py
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:

# -*- coding: utf-8 -*-
# @Time : 2019/8/1 15:40
# @Author : wujf
# @Email : 1028540310@qq.com
# @File : weather.py
# @Software: PyCharm import scrapy
from weather.items import WeatherItem class weather(scrapy.Spider):
name = 'weather'
allowed_domains = ['www.weather.com.cn/weather/101280601.shtml']
start_urls = [
'http://www.weather.com.cn/weather/101280601.shtml'
] def parse(self, response):
'''
筛选信息的函数
date= 日期
temperaturature = 当天的温度
weather = 当天的天气
wind = 当天的风向
:param response:
:return:
'''
items = [] day = response.xpath('//ul[@class="t clearfix"]') for i in list(range(7)):
item = WeatherItem()
item['date']= day.xpath('./li['+str(i+1)+']/h1//text()').extract_first()
item['temperature'] = day.xpath('./li['+str(i+1)+']/p[@class="tem"]/i//text()').extract_first()
item['weather'] = day.xpath('./li['+str(i+1)+']/p[@class="wea"]//text()').extract_first()
item['wind'] = day.xpath('./li[' + str(i + 1) + ']/p[@class="win"]/i//text()').extract_first()
#print(item)
items.append(item) return items

  编写管道PIPELINE:

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

1.文本形式:最基本存储方式

2.json格式:方便调用

3.数据库:数据量比较大选择的存储方式

import os
import requests
import json
import codecs
import pymysql
'''文本方式''' class WeatherPipeline(object):
def process_item(self, item, spider):
#print(item)
#获取当前目录
base_dir = os.getcwd() #filename = base_dir+'\\data\\test.txt'
filename = r'E:\Python\weather\weather\data\test.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数据'''
class W2json(object):
def process_item(self, item, spider):
'''
讲爬取的信息保存到json
方便其他程序员调用
'''
base_dir = os.getcwd()
#filename = base_dir + '/data/weather.json'
filename = r'E:\Python\weather\weather\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

  

class W2mysql(object):
def process_item(self, item, spider):
'''
讲爬取的信息保存到mysql
'''
date = item['date']
temperature = item['temperature']
weather = item['weather']
wind = item['wind'] connection = pymysql.connect(
host = '127.0.0.1',
user = 'root',
passwd='root',
db = 'scrapy',
# charset='utf-8',
cursorclass = pymysql.cursors.DictCursor
)
try:
with connection.cursor() as cursor:
#创建更新值的sql语句
sql = """INSERT INTO `weather` (date, temperature, weather, wind) VALUES (%s, %s, %s, %s) """
cursor.execute(
sql,(date,temperature,weather,wind)
)
connection.commit() finally:
connection.close() return item

  

然后在settings.py里面配置下

'''
设置日志等级
   ERROR : 一般错误         WARNING : 警告         INFO : 一般的信息         DEBUG : 调试信息         默认的显示级别是DEBUG ''' LOG_LEVEL = 'INFO'
 
ITEM_PIPELINES = {
'weather.pipelines.WeatherPipeline': 300,
'weather.pipelines.W2json': 400,
'weather.pipelines.W2mysql': 300,
}
 

上面三个类就展示三种数据整理方式。

最后运行scrapy  crawl weather得到三种结果:

 最后写个定时爬区任务

# -*- coding: utf-8 -*-
# @Time : 2019/8/3 15:38
# @Author : wujf
# @Email : 1028540310@qq.com
# @File : 定时爬虫.py
# @Software: PyCharm '''
第一种方法 采用sleep
'''
# import time
# import os
# while True:
# os.system('scrapy crawl weather')
# time.sleep(3) # 第二种
from scrapy import cmdline
import os #retal = os.getcwd() #获取当前目录
#print(retal)
os.chdir(r'E:\Python\weather\weather') #改变目录 因为只有进入scrapy框架才能执行scrapy crawl weather
cmdline.execute(['scrapy', 'crawl', 'weather'])

  还有一个中间件,但是我手上没有代理ip ,所以暂时玩不了。

OK,到此结束!

scrapy框架综合运用 爬取天气预报 + 定时任务的更多相关文章

  1. 基于scrapy框架输入关键字爬取有关贴吧帖子

    基于scrapy框架输入关键字爬取有关贴吧帖子 站点分析 首先进入一个贴吧,要想达到输入关键词爬取爬取指定贴吧,必然需要利用搜索引擎 点进看到有四种搜索方式,分别试一次,观察url变化 我们得知: 搜 ...

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

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

  3. Scrapy 框架 使用 selenium 爬取动态加载内容

    使用 selenium 爬取动态加载内容 开启中间件 DOWNLOADER_MIDDLEWARES = { 'wangyiPro.middlewares.WangyiproDownloaderMidd ...

  4. Scrapy框架——使用CrawlSpider爬取数据

    引言 本篇介绍Crawlspider,相比于Spider,Crawlspider更适用于批量爬取网页 Crawlspider Crawlspider适用于对网站爬取批量网页,相对比Spider类,Cr ...

  5. 使用scrapy框架来进行抓取的原因

    在python爬虫中:使用requests + selenium就可以解决将近90%的爬虫需求,那么scrapy就是解决剩下10%的吗? 这个显然不是这样的,scrapy框架是为了让我们的爬虫更强大. ...

  6. scrapy之360图片爬取

    #今日目标 **scrapy之360图片爬取** 今天要爬取的是360美女图片,首先分析页面得知网页是动态加载,故需要先找到网页链接规律, 然后调用ImagesPipeline类实现图片爬取 *代码实 ...

  7. 和风api爬取天气预报数据

    ''' 和风api爬取天气预报数据 目标:https://free-api.heweather.net/s6/weather/forecast?key=cc33b9a52d6e48de85247779 ...

  8. 爬虫系列---scrapy全栈数据爬取框架(Crawlspider)

    一 简介 crawlspider 是Spider的一个子类,除了继承spider的功能特性外,还派生了自己更加强大的功能. LinkExtractors链接提取器,Rule规则解析器. 二 强大的链接 ...

  9. Scrapy爬虫框架(实战篇)【Scrapy框架对接Splash抓取javaScript动态渲染页面】

    (1).前言 动态页面:HTML文档中的部分是由客户端运行JS脚本生成的,即服务器生成部分HTML文档内容,其余的再由客户端生成 静态页面:整个HTML文档是在服务器端生成的,即服务器生成好了,再发送 ...

随机推荐

  1. 新的起航从这里开始 Encantado!

    大家好,我是一名DBA之前也在其它地方写过blog,但是可惜目前在greatwall之内都不能访问了. 如果有小伙伴可以在墙外访问的话 可以尝试着看看这个地址 https://liuleiit.wix ...

  2. Ansible: hosts文件拆分为inventory和定义inventory全局变量

    前言 随着管理机器的增多,我们在使用Ansible的时候时常会遇到hosts文件过于冗长的问题,极其不便于管理,而将hosts文件拆分为inventory就可解决该问题:另外,hosts中的每个主机条 ...

  3. Linux命令行与Shell脚本编程大全

    快来参加<Linux命令行与Shell脚本编程大全>学习吧,提升技能,展示自我. 点击链接即可进入学习:https://s.imooc.com/WTmCO6H 课程亮点适合零基础读者,从零 ...

  4. Jmeter之设置动态关联

    前言 在Jmeter中,如何进行接口关联(上一个接口的返回参数作为下一个接口的入参使用)测试呢?下面我们一起来学习吧! 需求:需要利用商品信息接口的返回结果skuName值作为下一个登录接口参数Use ...

  5. FastDFS 配置文件 tracker.conf

    FastDFS 版本5.05 配置文件分为三部分   控制器:tracker.conf存储器:storage.conf 客户端:client.conf 文件位置:/etc/fdfs 基本配置(基础配置 ...

  6. Python3标准库:pprint美观打印数据结构

    1. pprint美观打印数据结构 pprint模块包含一个“美观打印机”,用于生成数据结构的一个美观的视图.格式化工具会生成数据结构的一些表示,不仅能够由解释器正确地解析,还便于人阅读.输出会尽可能 ...

  7. net start MySQL57 MySQL57 服务正在启动 . MySQL57 服务无法启动。

    造成这种情况的原因有很多,如果直接百度错误信息的话,不一定能很快解决问题,所以,出现这种情况,我们可以使用 mysqld --console 命令来查看报错信息,然后根据报错信息来百度,这样就很快定位 ...

  8. MyBatis XML配置properties

    来源:https://www.w3cschool.cn/mybatis/7zy61ilv.html XML 映射配置文件 MyBatis 的配置文件包含了影响 MyBatis 行为甚深的设置(sett ...

  9. Git学习笔记(windows git之初体验)

    阿里国内镜像地址: https://npm.taobao.org/mirrors/git-for-windows/ 最近在学习廖雪峰老师关于git的教程,链接可以在我的首页找到.首先使用国内镜像下载并 ...

  10. vue中this在回调函数中的使用

    this在各类回调中使用: 如果是普通函数是没法使用的 所以需要先将this.变量赋值给新的变量,然后才能在回调函数中使用 例如: refund: function (id) { if (!this. ...