上次做了一个双色球的数据爬取,其实大乐透的爬取也很简单,使用request就可以爬取,但是为了更好的进步,这次爬取大乐透采用了scrapy框架。

scrapy框架的运行机制不介绍了,不懂的先去google了解下吧;

..

..

一、创建项目

我使用的是windows进行开发的,所以需要在windows上安装好scrapy;假设已安装好该框架;

1、打开cmd,运行

scrapy startproject lottery_spider

命令,会在命令运行的文件下生成一个lottery_spider的项目

.

2、再执行 cd lottery_spider 进入lottery_spider项目,执行

scrapy gensiper lottery "www.lottery.gov.cn"

lottery 为爬虫文件;

www.lottery.gov.cn 为目标网站;

创建完毕后会在项目的 spider文件夹下生成爬虫文件: lottery.py

..

..

二、项目内的各个文件代码

1、items.py

# -*- coding: utf-8 -*-

# Define here the models for your scraped items

#

# See documentation in:

# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy

class LotterySpiderItem(scrapy.Item):

qihao = scrapy.Field()

bule_ball = scrapy.Field()

red_ball = scrapy.Field()

此文件定义了数据的模型,就是数据的参数;qihao、bule_ball、red_ball ;

.

2、lottery.py

# -*- coding: utf-8 -*-

import scrapy

from lottery_spider.items import LotterySpiderItem

class LotterySpider(scrapy.Spider):

name = 'lottery'

allowed_domains = ['gov.cn'] #允许爬虫爬取目标网站的域名,此域名之外的不会爬取;

start_urls = ['http://www.lottery.gov.cn/historykj/history_1.jspx?_ltype=dlt'] #起始页;从合格web开始爬取;

def parse(self, response):

#使用xpath获取数据前的路径,返回一个list的格式数据;

results = response.xpath("//div[@class='yylMain']//div[@class='result']//tbody//tr")

for result in results: #results数据需要for循环遍历;

qihao = result.xpath(".//td[1]//text()").get()

bule_ball_1 = result.xpath(".//td[2]//text()").get()

bule_ball_2 = result.xpath(".//td[3]//text()").get()

bule_ball_3 = result.xpath(".//td[4]//text()").get()

bule_ball_4 = result.xpath(".//td[5]//text()").get()

bule_ball_5 = result.xpath(".//td[6]//text()").get()

red_ball_1 = result.xpath(".//td[7]//text()").get()

red_ball_2 = result.xpath(".//td[8]//text()").get()

bule_ball_list = [] #定义一个列表,用于存储五个蓝球

bule_ball_list.append(bule_ball_1)

bule_ball_list.append(bule_ball_2)

bule_ball_list.append(bule_ball_3)

bule_ball_list.append(bule_ball_4)

bule_ball_list.append(bule_ball_5)

red_ball_list = [] #定义一个列表,用于存储2个红球

red_ball_list.append(red_ball_1)

red_ball_list.append(red_ball_2)

print("===================================================")

print("❤期号:"+ str(qihao) + " ❤" + "蓝球:"+ str(bule_ball_list) + " ❤" + "红球" + str(red_ball_list))

item = LotterySpiderItem(qihao = qihao,bule_ball = bule_ball_list,red_ball = red_ball_list)

yield item

next_url = response.xpath("//div[@class='page']/div/a[3]/@href").get()

if not next_url:

return

else:

last_url = "http://www.lottery.gov.cn/historykj/" + next_url

yield scrapy.Request(last_url,callback=self.parse) #这里调用parse方法的时候不用加();

此文件是运行的爬虫文件;

.

3、pipelines.py

# -*- coding: utf-8 -*-

# Define your item pipelines here

#

# Don't forget to add your pipeline to the ITEM_PIPELINES setting

# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html

import json

class LotterySpiderPipeline(object):

def __init__(self):

print("爬虫开始......")

self.fp = open("daletou.json", 'w', encoding='utf-8') # 打开一个json文件

def process_item(self, item, spider):

item_json = json.dumps(dict(item), ensure_ascii=False) #注意此处的item,需要dict来进行序列化;

self.fp.write(item_json + '\n')

return item

def close_spider(self,spider):

self.fp.close()

print("爬虫结束......")

此文件负责数据的保存,代码中将数据保存为了json数据;

.

4、settings.py

# -*- coding: utf-8 -*-

# Scrapy settings for lottery_spider project

#

# For simplicity, this file contains only settings considered important or

# commonly used. You can find more settings consulting the documentation:

#

# https://docs.scrapy.org/en/latest/topics/settings.html

# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html

# https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'lottery_spider'

SPIDER_MODULES = ['lottery_spider.spiders']

NEWSPIDER_MODULE = 'lottery_spider.spiders'

# Crawl responsibly by identifying yourself (and your website) on the user-agent

#USER_AGENT = 'lottery_spider (+http://www.yourdomain.com)'

# Obey robots.txt rules

ROBOTSTXT_OBEY = False #False,不去寻找网站设置的rebots.txt文件;

# Configure maximum concurrent requests performed by Scrapy (default: 16)

#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)

# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay

# See also autothrottle settings and docs

DOWNLOAD_DELAY = 1 #配置爬虫速度,1秒一次

# The download delay setting will honor only one of:

#CONCURRENT_REQUESTS_PER_DOMAIN = 16

#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)

#COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)

#TELNETCONSOLE_ENABLED = False

# Override the default request headers:

DEFAULT_REQUEST_HEADERS = { #配置爬虫的请求头,模拟浏览器请求;

'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',

'Accept-Language': 'en',

'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'

}

# Enable or disable spider middlewares

# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html

#SPIDER_MIDDLEWARES = {

# 'lottery_spider.middlewares.LotterySpiderSpiderMiddleware': 543,

#}

# Enable or disable downloader middlewares

# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html

#DOWNLOADER_MIDDLEWARES = {

# 'lottery_spider.middlewares.LotterySpiderDownloaderMiddleware': 543,

#}

# Enable or disable extensions

# See https://docs.scrapy.org/en/latest/topics/extensions.html

#EXTENSIONS = {

# 'scrapy.extensions.telnet.TelnetConsole': None,

#}

# Configure item pipelines

# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html

ITEM_PIPELINES = { #取消此配置的注释,让pipelines.py可以运行;

'lottery_spider.pipelines.LotterySpiderPipeline': 300,

}

# Enable and configure the AutoThrottle extension (disabled by default)

# See https://docs.scrapy.org/en/latest/topics/autothrottle.html

#AUTOTHROTTLE_ENABLED = True

# The initial download delay

#AUTOTHROTTLE_START_DELAY = 5

# The maximum download delay to be set in case of high latencies

#AUTOTHROTTLE_MAX_DELAY = 60

# The average number of requests Scrapy should be sending in parallel to

# each remote server

#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0

# Enable showing throttling stats for every response received:

#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)

# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings

#HTTPCACHE_ENABLED = True

#HTTPCACHE_EXPIRATION_SECS = 0

#HTTPCACHE_DIR = 'httpcache'

#HTTPCACHE_IGNORE_HTTP_CODES = []

#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

此文件是整个爬虫项目的运行配置文件;

.

5、start.py

from scrapy import cmdline

cmdline.execute("scrapy crawl lottery".split())

#等价于 ↓

# cmdline.execute(["scrapy","crawl","xiaoshuo"])

此文件是新建的文件,配置后就不用cmd中执行命令运行项目了;

python大乐透代码_scrapy框架爬取大乐透数据相关推荐

  1. 大乐透python预测程序_scrapy框架爬取大乐透数据

    [Python] 纯文本查看 复制代码# -*- coding: utf-8 -*- # Scrapy settings for lottery_spider project # # For simp ...

  2. java 使用webmagic 爬虫框架爬取博客园数据

    java 使用webmagic 爬虫框架爬取博客园数据存入数据库 学习记录   webmagic简介: WebMagic是一个简单灵活的Java爬虫框架.你可以快速开发出一个高效.易维护的爬虫. ht ...

  3. 【python爬虫02】使用Scrapy框架爬取拉勾网招聘信息

    使用Scrapy框架爬取拉勾网招聘信息 最近接触了Scrapy爬虫框架,简单写了个爬虫爬取拉钩网的招聘信息,加深对Scrapy框架的理解,不得不说Scrapy框架其实还是蛮方便的,就像爬虫流水线一样, ...

  4. scrapy框架爬取王者荣耀英雄数据

    scrapy框架爬取王者荣耀英雄属性 爬虫工程 爬虫文件 import scrapy from theKingPro.items import ThekingproItemclass ThekingS ...

  5. python爬取4399小游戏数据_25行代码带你爬取4399小游戏数据,看下童年的游戏是否还在...

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,如有问题请及时联系我们以作处理. 还记得童年的网页小游戏吗?今天带大家爬取4399小游戏网站的数据,游戏名字+链接地址 目标网 ...

  6. requests 分类多级页面_scrapy框架爬取多级页面

    spides.py # -*- coding: utf-8 -*- import scrapy from weather.items import WeatherItem from scrapy.cr ...

  7. python中scrapy可以爬取多少数据_python中scrapy框架爬取携程景点数据

    ------------------------------- [版权申明:本文系作者原创,转载请注明出处] 文章出处:https://blog.csdn.net/sdksdk0/article/de ...

  8. python爬虫怎么爬小说_小白的python爬虫,40代码教你爬取豆瓣小说

    这篇文章写了很久了,一直没有发布: 爬虫学的差不多了,觉得这篇文章对新手实践还是有些作用的.毕竟这也是我刚学爬虫的时候练习的,爬取了比较好爬的网站,也比较经典:多余的解释不说了,代码里每一行都有注释, ...

  9. python爬取豆瓣代码_小白的python爬虫,40代码教你爬取豆瓣小说

    这篇文章写了很久了,一直没有发布: 爬虫学的差不多了,觉得这篇文章对新手实践还是有些作用的.毕竟这也是我刚学爬虫的时候练习的,爬取了比较好爬的网站,也比较经典:多余的解释不说了,代码里每一行都有注释, ...

最新文章

  1. Ubuntu 更新后 VirtualBox 无法启动
  2. 《那些年啊,那些事——一个程序员的奋斗史》——61
  3. php array walk recursive,php中如何使用array_walk_recursive?
  4. 项目管理工具之SWOT分析法
  5. ViolentMonkey暴力猴插件V2.13.0
  6. 【光学设计基础】--01像差理论基础
  7. (梳理)用Tensorflow实现SE-ResNet(SENet ResNet ResNeXt VGG16)的数据输入,训练,预测的完整代码框架(cifar10准确率90%)
  8. 高效能人士的七个习惯——由内而外全面造就自己
  9. android开发动态图ae,动影ae动态图片特效制作
  10. MySQL事务之不可重复读问题
  11. 【多目标优化】3. 基于分解的多目标进化算法 —(MOEA/D)
  12. 阿里云国际版如何将ECS云服务器中的数据备份到本地
  13. 玩转冷板式液冷 你需要一份靠谱的“设计参考”
  14. 洗衣机程序c语言代码大全,全自动洗衣机控制器设计的单片机代码
  15. Altium Designer布局布线时元器件移动
  16. 逆向学习litevm篇
  17. c语言xdoj上机题 字符输入输出
  18. 山东大学计算机学院夏令营经验贴.2019
  19. 7月26日科技联播:物联网技术可确保疫苗运输安全,NASA深入极旱之地为寻找火星生命遗迹做准备...
  20. 视频、音频文件格式大全

热门文章

  1. 再次思考:xdb和无锁2种设计方案
  2. H264的基本原理(二)------ H264编码原理
  3. Mac mini M1 2K显示器
  4. C++ 单冒号: 和双冒号:: 的作用
  5. 中国公司使用巴西文字插图介绍产品?
  6. 最新版计算机软件著作权登记申请表填写说明
  7. ORBSLAM3阅读笔记1 System
  8. 台式计算机组装与应用论文,计算机组装与维护论文
  9. 计算机科学导论第六章计算机网路 学习笔记+习题答案
  10. vxe-table合并单元格后增加选中效果