爬取目标网站:

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. js算法题

    //较Low,看到的大神 帮补充 1.给定一个数组:,定义一个函数获取数组中所有的奇数,返回一个新数组:var arr1=[1,3,4,5,6,7,8,3,4,2,3,6];    function ...

  2. Java Properties的使用

    转自:https://www.cnblogs.com/bakari/p/3562244.html 一.Java Properties类 Java中有个比较重要的类Properties(Java.uti ...

  3. ELF文件之五——使用链接脚本-2个函数-data-bss

    main.c int enable; ; int main() { ; } int add() { ; } bss段在elf中虽然size是4,但并不占filesize,节头表如下图所示 程序头中,项 ...

  4. light oj1028 - Trailing Zeroes (I)

    1028 - Trailing Zeroes (I)   We know what a base of a number is and what the properties are. For exa ...

  5. vue element 表头添加斜线

    <template> <div class="app-container"> <el-table :data="tableData3&quo ...

  6. Spring ioc(4)---如何解决循环依赖

    前面说到对象的创建,那么在创建的过程中Spring是怎么又是如何解决循环依赖的呢.前面提到有个三级缓存.就是利用这个来解决循环依赖.打个比方说实例化A的时候,先将A创建(早期对象)放入一个池子中.这个 ...

  7. http各个版本(1/1.1/2)对比

    参考的文章: 从理论到实践 全面理解HTTP/2 HTTP协议以及HTTP2.0/1.1/1.0区别 综合阐述http1.0/1.1/2和https 目录: http1.1 长连接 HTTP 1.1支 ...

  8. [红日安全]Web安全Day2 - XSS跨站实战攻防

    本文由红日安全成员: Aixic 编写,如有不当,还望斧正. 大家好,我们是红日安全-Web安全攻防小组.此项目是关于Web安全的系列文章分享,还包含一个HTB靶场供大家练习,我们给这个项目起了一个名 ...

  9. Http API触发小程序云函数案例

    1.创建云函数 在云开发中创建云函数(sum,调用需要两个参数:a.b): 2.invokeCloudFunction触发云函数 const request = require('request'); ...

  10. Hadoop-HDFS(HDFS-HA)

    HDFS(Hadoop Distributed File System) 分布式文件系统,HDFS是一个高度容错性的系统,适合部署在廉价的机器上.HDFS能提供高吞吐量的数据访问,非常适合大规模数据集 ...