爬取目标网站:

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. 11--Java--JDBC知识梳理

    JDBC 一.概述:JDBC(java database connection),使用java语言连接数据库,是java提供一套操作数据库的接口(标准),实现对数据库的统一访问,是一个java引用应用 ...

  2. error C2662

    原因:关于const的问题 具体错误:函数的参数列表中参数签名为const,但是却调用了该参数的非const的成员函数 例子: 即使我们知道NoConst()并不会改变类的data成员,编译器依旧会报 ...

  3. [redis读书笔记] 第二部分 单机数据库 数据库实现

    一 数据库基本实现/命令下发的实现 redis.c里,大家能看到redisCommandTable[] 的实现,列出了支持的所有命令.大部分的入参为redisClient *c,当一条REDIS命令下 ...

  4. Java开发最佳实践(二) ——《Java开发手册》之"异常处理、MySQL 数据库"

    二.异常日志 (一) 异常处理 (二) 日志规约 三.单元测试 四.安全规约 五.MySQL数据库 (一) 建表规约 (二) 索引规约 (三) SQL语句 (四) ORM映射 六.工程结构 七.设计规 ...

  5. ELF文件之九——使用链接脚本-2个函数-data-bss-temp-call-debug信息-struct

    main.c int enable; ; struct aaa { int membera; char memberb; }s_aaa; int main() { int temp; add(); d ...

  6. 高并发之——深入解析Callable接口

    本文纯干货,从源码角度深入解析Callable接口,希望大家踏下心来,打开你的IDE,跟着文章看源码,相信你一定收获不小. 1.Callable接口介绍 Callable接口是JDK1.5新增的泛型接 ...

  7. Web渗透测试漏洞手册及修复建议

    Web渗透测试漏洞手册及修复建议 0x0 配置管理 0x01 HTTP方法测试 漏洞介绍: 目标服务器启用了不安全的传输方法,如PUT.DELETE等,这些方法表示可能在服务器上使用了 WebDAV, ...

  8. Windows-server-2008-R2安装Oracle-11g-R2-dataguard

    一.安装环境 1.服务器环境:Windows server 2008 R2 x64 Standard 两台 CPU:8核 内存:8G 硬盘空间:1060G 2.软件:oracle 11g R2 二.安 ...

  9. U盘制作macOS Sierra的启动盘

    1.macOS Sierra的几种安装方式 *开机时按住command+option+r 进行联网在线安装.PS:在网速好的情况还行,但是如果网络差的时候,它会让你崩溃的. *使用光盘进行安装. *今 ...

  10. Sublime text3的安装以及python开发环境的搭建

    作者:struct_mooc 博客地址:https://www.cnblogs.com/structmooc/p/12376601.html 一. Sublime text3的安装 1.sublime ...