爬虫双色球所有的历史数据并保存到SQLite
前言
上一篇介绍了双色球走势图是怎么实现的,这一篇介绍怎么实现爬虫所有的双色球历史数据,也可以同步分享怎么同步福彩3D数据。采用的C#来实现的。
同步双色球的地址:https://datachart.500.com/ssq/history/newinc/history.php?start={0}&end={1}
同步福彩3D的地址:https://datachart.500.com/sd/history/inc/history.php?start={0}&end={1}
上一篇介绍走势图的实现:https://www.cnblogs.com/luoyuhao/p/13887935.html
打开网站显示的数据如下:
实现爬虫的过程
创建接收存储双色球历史数据的table
抓取网站上的html ,再通过html 去解析相应的数据。
通过以上截取后就只剩下需要的双色球的历史数据了,再去截取tr td数据,就相应能到得到相应的数据了,是不是很简单的一件事呀!
解析tr所有数据
/// <summary>
/// 双色球TR
/// </summary>
/// <param name="wnRepo"></param>
/// <param name="content"><tbody></tbody>之间的内容</param>
private void ResolveSSQTr(string content)
{
string trContent = string.Empty;
Regex regex = new Regex("<tr class=\"t_tr1\">");
//在<tbody></tbody>之间的内容搜索所有匹配<tr>的项
MatchCollection matches = regex.Matches(content);
foreach (Match item in matches)
{
//如果当前匹配项的下一个匹配项的值不为空
if (!string.IsNullOrEmpty(item.NextMatch().Value))
{
trContent = content.Substring(item.Index, item.NextMatch().Index - item.Index);
}
//最后一个<tr>的匹配项
else
{
trContent = content.Substring(item.Index, content.Length - item.Index);
}
DataRow dr = ssqdt.NewRow();
ResolveSSQTd(ref dr, trContent); ssqdt.Rows.Add(dr);
}
}
解析所有td内容
/// <summary>
/// 双色球TD
/// </summary>
/// <param name="dr"></param>
/// <param name="trContent"></param>
private void ResolveSSQTd(ref DataRow dr, string trContent)
{
List<int> redBoxList = null;
//匹配期号的表达式
string patternQiHao = "<td>";
Regex regex = new Regex(patternQiHao);
Match qhMatch = regex.Match(trContent);
dr["QiHao"] = trContent.Substring(qhMatch.Index + 13 + patternQiHao.Length, 5); if (int.Parse(trContent.Substring(qhMatch.Index + 13 + patternQiHao.Length, 5)) % 2 == 0)
{
dr["Type"] = "双期";
}
else
{
dr["Type"] = "单期";
} //存放匹配出来的红球号码
redBoxList = new List<int>();
//匹配红球的表达式
string patternChartBall = "<td class=\"t_cfont2\">";
regex = new Regex(patternChartBall);
MatchCollection rMatches = regex.Matches(trContent);
foreach (Match r in rMatches)
{
redBoxList.Add(Convert.ToInt32(trContent.Substring(r.Index + patternChartBall.Length, 2)));
} //匹配红球的表达式
patternChartBall = "<td class=\"t_cfont4\">";
regex = new Regex(patternChartBall);
rMatches = regex.Matches(trContent); foreach (Match r in rMatches)
{
dr["B"] = Convert.ToInt32(trContent.Substring(r.Index + patternChartBall.Length, 2));
break;
} patternChartBall = @"\d{4}-\d{2}-\d{2}";
regex = new Regex(patternChartBall);
rMatches = regex.Matches(trContent);
foreach (Match r in rMatches)
{
DateTime dt = Convert.ToDateTime(r.Value);
dr["OpenDate"] = dt;
dr["Week"] = CaculateWeekDay(dt.Year, dt.Month, dt.Day);
} //排序红球号码
redBoxList.Sort();
//红球号码
dr["R1"] = redBoxList[0];
dr["R2"] = redBoxList[1];
dr["R3"] = redBoxList[2];
dr["R4"] = redBoxList[3];
dr["R5"] = redBoxList[4];
dr["R6"] = redBoxList[5];
dr["HTML"] = trContent;
}
保存所解析的数据保存到SQLite
if (!Directory.Exists(tempPath))//判断文件夹是否存在
Directory.CreateDirectory(tempPath);//创建文件夹在根目录下
string _db = System.IO.Path.Combine(tempPath, "cpdb.dll");
SQLiteHelper helper = new SQLiteHelper(_db);
OperResult oper = new OperResult(); helper.ExecuteNonQuery(string.Format("drop table if exists {0}", ssqtableName), _db); string msg = string.Format("create table if not exists {0} (\r\n", ssqtableName);
for (int i = 0; i < ssqdt.Columns.Count; i++)
{
msg += string.Format("{0} {1},\r\n", ssqdt.Columns[i].ColumnName, helper.TypeToSqliteType(ssqdt.Columns[i].DataType));
}
msg = msg.Remove(msg.LastIndexOf(",\r\n"), 3);
msg += ")"; oper = helper.ExecuteNonQuery(msg, _db);
oper = helper.SaveDataTable(ssqdt, ssqtableName);
获取网页内容的方法
public static string HttpGet(string url,string encoding)
{
WebRequest request = HttpWebRequest.Create(url);
WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream, Encoding.GetEncoding(encoding));
string content = reader.ReadToEnd();
return content;
}
基姆拉尔森计算公式计算日期
/// <summary>
/// 基姆拉尔森计算公式计算日期
/// </summary>
/// <param name="y">年</param>
/// <param name="m">月</param>
/// <param name="d">日</param>
/// <returns>星期几</returns>
protected string CaculateWeekDay(int y, int m, int d)
{
if (m == 1 || m == 2)
{
m += 12;
y--;
//把一月和二月看成是上一年的十三月和十四月,例:如果是2004-1-10则换算成:2003-13-10来代入公式计算。
}
int week = (d + 2 * m + 3 * (m + 1) / 5 + y + y / 4 - y / 100 + y / 400) % 7;
string weekstr = "";
switch (week)
{
case 0: weekstr = "周一"; break;
case 1: weekstr = "周二"; break;
case 2: weekstr = "周三"; break;
case 3: weekstr = "周四"; break;
case 4: weekstr = "周五"; break;
case 5: weekstr = "周六"; break;
case 6: weekstr = "周日"; break;
}
return weekstr;
}
保存完后,显示的形式就是以DLL结尾的文件了,如下图:
怎么读取保存的双色球数据
string _db = System.IO.Path.Combine(tempPath, "cpdb.dll");
SQLiteHelper helper = new SQLiteHelper(_db);
OperResult oper = new OperResult();
oper = helper.GetDataSet(string.Format("select * from {0}", ssqtableName), _db);
if (oper.State == 1 && oper.DataSet != null && oper.DataSet.Tables.Count > 0 && oper.DataSet.Tables[0].Rows.Count > 0)
{
ViewBag.QiHao = "第" + oper.DataSet.Tables[0].Rows[0]["QiHao"] + "期";
ViewBag.B = oper.DataSet.Tables[0].Rows[0]["B"].ToString().Length == 1 ? "0" + oper.DataSet.Tables[0].Rows[0]["B"].ToString() : oper.DataSet.Tables[0].Rows[0]["B"].ToString();
ViewBag.R1 = oper.DataSet.Tables[0].Rows[0]["R1"].ToString().Length == 1 ? "0" + oper.DataSet.Tables[0].Rows[0]["R1"].ToString() : oper.DataSet.Tables[0].Rows[0]["R1"].ToString();
ViewBag.R2 = oper.DataSet.Tables[0].Rows[0]["R2"].ToString().Length == 1 ? "0" + oper.DataSet.Tables[0].Rows[0]["R2"].ToString() : oper.DataSet.Tables[0].Rows[0]["R2"].ToString();
ViewBag.R3 = oper.DataSet.Tables[0].Rows[0]["R3"].ToString().Length == 1 ? "0" + oper.DataSet.Tables[0].Rows[0]["R3"].ToString() : oper.DataSet.Tables[0].Rows[0]["R3"].ToString();
ViewBag.R4 = oper.DataSet.Tables[0].Rows[0]["R4"].ToString().Length == 1 ? "0" + oper.DataSet.Tables[0].Rows[0]["R4"].ToString() : oper.DataSet.Tables[0].Rows[0]["R4"].ToString();
ViewBag.R5 = oper.DataSet.Tables[0].Rows[0]["R5"].ToString().Length == 1 ? "0" + oper.DataSet.Tables[0].Rows[0]["R5"].ToString() : oper.DataSet.Tables[0].Rows[0]["R5"].ToString();
ViewBag.R6 = oper.DataSet.Tables[0].Rows[0]["R6"].ToString().Length == 1 ? "0" + oper.DataSet.Tables[0].Rows[0]["R6"].ToString() : oper.DataSet.Tables[0].Rows[0]["R6"].ToString();
}
以上即完成双色球历史数据的爬虫和保存数据的全部过程,思路非常清晰,而且方法容易,这样就不需要调用收费的接口了,为开发双色球走势图打好良好的基础 ,大家有没有觉得非常容易呀!其实爬虫的方法很多,希望跟大家一起交流学习了,也可以通过正则表达是来获取相应的数据,也可以用第三方工具去解析更简单快捷,曾经我也做过相应的爬虫,还挺好玩的。
爬虫福彩3D数据
同样显示创建接收数据的表结构来接收数据。
解析tr数据
string trContent = string.Empty;
Regex regex = new Regex("<tr>");
//在<tbody></tbody>之间的内容搜索所有匹配<tr>的项
MatchCollection matches = regex.Matches(content);
foreach (Match item in matches)
{
//如果当前匹配项的下一个匹配项的值不为空
if (!string.IsNullOrEmpty(item.NextMatch().Value))
{
trContent = content.Substring(item.Index, item.NextMatch().Index - item.Index);
}
//最后一个<tr>的匹配项
else
{
trContent = content.Substring(item.Index, content.Length - item.Index);
}
//DataRow dr = sddt.NewRow(); ResolveSDSJTd(trContent); //sddt.Rows.Add(dr);
}
解析td数据
private void ResolveSDSJTd(string trContent)
{
string patternChartBall = @"[1-9]\d{6}";
Regex regex = new Regex(patternChartBall);
MatchCollection rMatches = regex.Matches(trContent);
string qihao = "";
foreach (Match r in rMatches)
{
qihao = r.Value;
break;
} patternChartBall = "<td class=\"chartBall01\" width=18>";
regex = new Regex(patternChartBall);
rMatches = regex.Matches(trContent);
List<int> redBoxList = new List<int>(); foreach (Match r in rMatches)
{
int xx = int.Parse(trContent.Substring(r.Index + patternChartBall.Length, 1));
redBoxList.Add(xx);
} if (!string.IsNullOrEmpty(qihao))
{
DataRow[] dr = sddt.Select(string.Format("QiHao='{0}'", qihao));
if (dr.Length > 0)
{
dr[0]["R4"] = redBoxList[0];
dr[0]["R5"] = redBoxList[1];
dr[0]["R6"] = redBoxList[2];
}
}
}
保存数据
if (!Directory.Exists(tempPath))//判断文件夹是否存在
Directory.CreateDirectory(tempPath);//创建文件夹在根目录下
string _db = System.IO.Path.Combine(tempPath, "sddb.dll");
SQLiteHelper helper = new SQLiteHelper(_db);
OperResult oper = new OperResult(); helper.ExecuteNonQuery(string.Format("drop table if exists {0}", sdtableName), _db); string msg = string.Format("create table if not exists {0} (\r\n", sdtableName);
for (int i = 0; i < sddt.Columns.Count; i++)
{
msg += string.Format("{0} {1},\r\n", sddt.Columns[i].ColumnName, helper.TypeToSqliteType(sddt.Columns[i].DataType));
}
msg = msg.Remove(msg.LastIndexOf(",\r\n"), 3);
msg += ")"; oper = helper.ExecuteNonQuery(msg, _db);
oper = helper.SaveDataTable(sddt, sdtableName);
以上即可完成对福彩3D数据的爬虫,还能爬取福彩3D试机号,这些数据一些就能全部爬取完了,非常的快捷简单方便。
双色球走势图如下:
上一篇文章有介绍怎么去实现双色球走势图,这里就不再过多介绍了,这一篇主要是介绍怎么爬虫双色球和福彩3D数据。
详细介绍:https://www.cnblogs.com/luoyuhao/p/13887935.html
后记
为了做好爬虫数据和走势图,爬虫技术只能为做好走势图是一个前提条件,两个步骤是相辅相成的,现在这两个技术都具备了,只是不断完善技术才能做出更强大的走势图的网站。以上只是纯技术交流和学习,欢迎大家一起留言交流,共同学习进步。
爬虫双色球所有的历史数据并保存到SQLite的更多相关文章
- Android把图片保存到SQLite中
1.bitmap保存到SQLite 中 数据格式:Blob db.execSQL("Create table " + TABLE_NAME + "( _id INTEGE ...
- Python scrapy爬虫数据保存到MySQL数据库
除将爬取到的信息写入文件中之外,程序也可通过修改 Pipeline 文件将数据保存到数据库中.为了使用数据库来保存爬取到的信息,在 MySQL 的 python 数据库中执行如下 SQL 语句来创建 ...
- Python爬虫中文小说网点查找小说并且保存到txt(含中文乱码处理方法)
从某些网站看小说的时候经常出现垃圾广告,一气之下写个爬虫,把小说链接抓取下来保存到txt,用requests_html全部搞定,代码简单,容易上手. 中间遇到最大的问题就是编码问题,第一抓取下来的小说 ...
- node 爬虫 --- 将爬取到的数据,保存到 mysql 数据库中
步骤一:安装必要模块 (1)cheerio模块 ,一个类似jQuery的选择器模块,分析HTML利器. (2)request模块,让http请求变的更加简单 (3)mysql模块,node连接mysq ...
- 吴裕雄--天生自然PYTHON爬虫:安装配置MongoDBy和爬取天气数据并清洗保存到MongoDB中
1.下载MongoDB 官网下载:https://www.mongodb.com/download-center#community 上面这张图选择第二个按钮 上面这张图直接Next 把bin路径添加 ...
- scrapy 保存到 sqlite3
scrapy 爬取到结果后,将结果保存到 sqlite3,有两种方式 item Pipeline Feed Exporter 方式一 使用 item Pipeline 有三个步骤 文件 pipelin ...
- python爬取当当网的书籍信息并保存到csv文件
python爬取当当网的书籍信息并保存到csv文件 依赖的库: requests #用来获取页面内容 BeautifulSoup #opython3不能安装BeautifulSoup,但可以安装Bea ...
- python scrapy实战糗事百科保存到json文件里
编写qsbk_spider.py爬虫文件 # -*- coding: utf-8 -*- import scrapy from qsbk.items import QsbkItem from scra ...
- jQuery切换网页皮肤保存到Cookie实例
效果体验:http://keleyi.com/keleyi/phtml/jqtexiao/25.htm 以下是源代码: <!DOCTYPE html PUBLIC "-//W3C//D ...
随机推荐
- 《Duubo系列》-Dubbo服务暴露过程
我今天来就带大家看看 Dubbo 服务暴露过程,这个过程在 Dubbo 中其实是很核心的过程之一,关乎到你的 Provider 如何能被 Consumer 得知并调用. 今天还是会进行源码解析,毕竟我 ...
- spring多模块之间的调用
https://blog.csdn.net/tomcat_2014/article/details/50206197?locationNum=5
- mysql5.7开启慢查询日志
环境:centos7 mysql版本:5.7.28 一.什么是慢查询 MySQL默认10s内没有响应SQL结果,则为慢查询 当然我们也可以修改这个默认时间 查看慢查询的时间 show variable ...
- c++中的#include "stdafx.h"
转自:https://blog.csdn.net/lijun5635/article/details/13090341 在网上看到的一篇很详细的文章解释,之前一直不明白这个头文件什么作用,用来学习很好 ...
- vs中CString的用法,以及所需的头文件
转载:https://blog.csdn.net/shizhandong50/article/details/13321505 1.CString类型的头文件#include <afx.h> ...
- matlab中exist 检查变量、脚本、函数、文件夹或类的存在情况
参考: 1.https://ww2.mathworks.cn/help/matlab/ref/exist.html?searchHighlight=exist&s_tid=doc_srchti ...
- Code Forces 1030E
题目大意: 给你n个数,你可以交换一个数的任意二进制位,问你可以选出多少区间经过操作后异或和是0. 思路分析: 根据题目,很容易知道,对于每个数,我们可以无视它的1在那些位置,只要关注它有几个1即可, ...
- git 上传文件到 gitee 码云远程仓库
一 , 想将码云仓库里面的代码,抓取下来 1.git remote add origin 地址 2. git remote -v 3. it pull origin master 二 , 将自己创建 ...
- 从0到1进行Spark history分析
一.总体思路 以上是我在平时工作中分析spark程序报错以及性能问题时的一般步骤.当然,首先说明一下,以上分析步骤是基于企业级大数据平台,该平台会抹平很多开发难度,比如会有调度日志(spark-sub ...
- 35岁老半路程序员的Python从0开始之路
9年的ERP程式开发与维护,继而转向一年的售前,再到三年半的跨行业务,近4的兜兜转转又转回来做程式了,不过与之前不同的,是这次是新的程序语言Python, 同时此次是为了教学生而学习! 从今天开始,正 ...