Python网络爬虫和信息提取:(动态网站)双色球数据爬取及写入数据库Sqlite、json和Excel表

我想着拿什么练习下网络爬虫信息提取时,就想到了双色球,心想把往期数据提取出来也是个不错的主意,把数据保存下来以后做数据分析,根据分析结果去买双色球岂不是美哉?!哈哈哈。。
当然这里仅是爬取和保存,数据分析就是后话了。
既然有了想法就准备开始吧。我准备提取中国福彩网的官网上双色球的往期数据,首先我们打开官网"http://www.cwl.gov.cn/"然后确认robots协议,是可以对网站进行爬取的(善意提醒:不要频繁爬取),那么就开始吧。
我们打开双色球往期开奖网页,查看源代码,发现并没有我们想要的数据,也就是这个是个动态网页,我们需要打开F12开发者工具,对我们需要的网页进行抓包。如下图所示,首先进到Network,然后点击XHR,在左边name栏查看哪个是我们所需要的,可以通过preview来确认。

在这里插入图片描述

在这里插入图片描述
我们确认了想要的数据后,那么这个url:”http://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueCount=30 “就是我们所需要的,打开网页内容如下:在这里插入图片描述
正是我们要的数据,而且是个超级简单的组成,但是在开始爬之前我们呢观察下网址,后面是Count=30这样组成的,那么很显然这是确定我们要爬取多少期的,所以我们可以手动输入想要的期数(注意最大提供100期的),如下所示:

cnt = input("请输入你要获取的数量(0-100]的整数:")
cntINT = int(cnt)
url = 'http://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueCount='+cnt

try:
    if(0<cntINT<=100):
        r = requests.get(url, timeout=30)
        r.raise_for_status()
        encoding = chardet.detect(r.content)['encoding']
        r.encoding = encoding
        demo = r.text
    else:
        print("请输入(0-100]的数")
except:
    print("获取数据失败")

这里想说明下encoding = chardet.detect(r.content)[‘encoding’],
因为这个apparent_encoding方法还是有几率会出现乱码,所以这里引用了chardet库来检测文本编码,还有个库为cChardet,看名字就知道这俩库是兄弟,具体啥区别不清楚,好像cChardet更快一点。但是我用的是python3.10,目前这个库还未有匹配版本,所以先用了chardet库。

然后通过BeautifulSoup获取标签内容:

soup = BeautifulSoup(demo, "html.parser")   

我们需要将获取的内容转为字典:

my_dict = []
my_dict02 = []
for s in soup:
    my_dict.append(s)
for m in my_dict[0]:
    my_dict02.append(m)
# print(my_dict02)
Dict_str = "".join(my_dict02)
new_dict = json.loads(Dict_str)

到这里我们已经爬到我们要的内容了,但是注意的是,我们真正需要的内容是在字典 key result的值内,所以我们在把他提出来:

final_dict = new_dict.get('result')           

到这里我们真正的爬到了我们要的内容,现在开始分别写入json,Sqlite和Excel中,首先写道json中,

with open('Ssq_data'+cnt+'.json', 'w',encoding='utf-8') as json_file:
     json.dump(final_dict, json_file, indent=4, ensure_ascii=False)

indent=4, ensure_ascii=False 是将其格式化,json内的内容如下:
在这里插入图片描述
格式化后的json数据看起来很漂亮。

然后我们将其写入数据库Sqlite,这里我们可以直接通过final_dict字典写入也可以通过我们建立的json数据写入都可以,首先建立我们的数据库:

conn = sqlite3.connect('Ssqdata'+cnt+'.sqlite')
cur = conn.cursor()

然后建立表格,因为我个人想要的数据为期号,开奖日期,红球号,蓝球号,所以需要四个表格,但是我还想建立两个关于红球和蓝球的,看看他们是否会有重复出现,所以需要六个表格:

cur.executescript('''
DROP TABLE IF EXISTS Ssq;
DROP TABLE IF EXISTS RE;
DROP TABLE IF EXISTS DATE;
DROP TABLE IF EXISTS BL;
DROP TABLE IF EXISTS Red;
DROP TABLE IF EXISTS Blue;

我的Ssq表格里是以期号来建立的,期号不会有重复所以比较保险,然后同时也想插入日期,红球和蓝球到这个表格里做一个汇总表格所以我们要如下建立:

//汇总表
CREATE TABLE Ssq (
    id     INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    code   TEXT UNIQUE,
    date   INTEGER,
    red    INTEGER,
    blue   INTEGER
);

CREATE TABLE DATE (
    id     INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    date   TEXT NOT NULL
);  

CREATE TABLE RE (
    id     INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    red   TEXT NOT NULL
);  
CREATE TABLE BL (
    id     INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    blue   TEXT NOT NULL
);    
//看看是否会有重复的出现(显然几率和中头奖差不多)
CREATE TABLE Red (
    id     INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    red    TEXT UNIQUE
);
//看看蓝球是不是有重复出现,因为是16内的单数所以大概率会出现重复的
CREATE TABLE Blue (  
    id     INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    blue   TEXT UNIQUE

)
''')

表格建好了就要写入数据:

//读入刚刚建立的json数据
str_data = open('Ssq_data'+cnt+'.json',mode='r', encoding='utf-8')
json_data = json.load(str_data)

for entry in json_data://也可以通过字典 final_dict 读入数据
    code = entry['code']
    date = entry['date']
    red = entry['red']
    blue = entry['blue']

    cur.execute('''INSERT OR IGNORE INTO Ssq (code,date,red,blue)
            VALUES ( ?,?,?,? )''', (code, date, red, blue))
    cur.execute('SELECT id FROM Ssq WHERE code = ? ', (code,))

    cur.execute('''INSERT OR IGNORE INTO DATE (date)
            VALUES ( ? )''', (date,))
    cur.execute('SELECT id FROM DATE WHERE date = ? ', (date,))

    cur.execute('''INSERT OR IGNORE INTO RE (red)
                VALUES ( ? )''', (red,))
    cur.execute('SELECT id FROM RE WHERE red = ? ', (red,))

    cur.execute('''INSERT OR IGNORE INTO Red (red)
                   VALUES ( ? )''', (red,))
    cur.execute('SELECT id FROM Red WHERE red = ? ', (red,))

    cur.execute('''INSERT OR IGNORE INTO BL (blue)
                   VALUES ( ? )''', (blue,))
    cur.execute('SELECT id FROM BL WHERE blue = ? ', (blue,))

    cur.execute('''INSERT OR IGNORE INTO Blue (blue)
                   VALUES ( ? )''', (blue,))
    cur.execute('SELECT id FROM Blue WHERE blue = ? ', (blue,))

    conn.commit()

这样就保存到数据库中,我们用DB Browser打开Ssqdata(cnt).sqlite文件,可以看到结果如下:
在这里插入图片描述
在这里插入图片描述
最后我们写入excel表中:

book = xlwt.Workbook(encoding='utf-8')
sheet = book.add_sheet('双色球')//建立sheet
//建立表头
sheet.write(0, 0, '期号')
sheet.write(0, 1, '开奖日期')
sheet.write(0, 2, '红球')
sheet.write(0, 3, '蓝球')
index =1
//写入数据
for entry in json_data:
    code = entry['code']
    date = entry['date']
    red = entry['red']
    blue = entry['blue']
    sheet.write(index, 0, code)
    sheet.write(index, 1, date)
    sheet.write(index, 2, red)
    sheet.write(index, 3, blue)
    index += 1
book.save(u"Ssq_data"+cnt+".xls")

结果如下:在这里插入图片描述
下面附上完整代码:

import  requests
from bs4 import BeautifulSoup
import json
import sqlite3
import chardet
import xlwt

cnt = input("请输入你要获取的数量(30,50,100):")
cntINT = int(cnt)
url = 'http://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueCount='+cnt

try:
    if(0<cntINT<=100):
        r = requests.get(url, timeout=30)
        r.raise_for_status()
        encoding = chardet.detect(r.content)['encoding']
        r.encoding = encoding
        demo = r.text
    else:
        print("请输入(0-100]的数")
except:
    print("获取数据失败")

//获取内容并转为字典
soup = BeautifulSoup(demo, "html.parser")
my_dict = []
my_dict02 = []
for s in soup:
    my_dict.append(s)
for m in my_dict[0]:
    my_dict02.append(m)
# print(my_dict02)
Dict_str = "".join(my_dict02)
new_dict = json.loads(Dict_str)
# print(new_dict)
final_dict = new_dict.get('result')

//写入json
with open('Ssq_data'+cnt+'.json', 'w',encoding='utf-8') as json_file:
     json.dump(final_dict, json_file, indent=4, ensure_ascii=False)

//建立数据库sqlite
conn = sqlite3.connect('Ssqdata'+cnt+'.sqlite')
cur = conn.cursor()
//建立表格
cur.executescript('''
DROP TABLE IF EXISTS Ssq;
DROP TABLE IF EXISTS RE;
DROP TABLE IF EXISTS DATE;
DROP TABLE IF EXISTS BL;
DROP TABLE IF EXISTS Red;
DROP TABLE IF EXISTS Blue;

CREATE TABLE Ssq (
    id     INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    code   TEXT UNIQUE,
    date   INTEGER,
    red    INTEGER,
    blue   INTEGER
);

CREATE TABLE DATE (
    id     INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    date   TEXT NOT NULL
);  

CREATE TABLE RE (
    id     INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    red   TEXT NOT NULL
);  
CREATE TABLE BL (
    id     INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    blue   TEXT NOT NULL
);    

CREATE TABLE Red (
    id     INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    red    TEXT UNIQUE
);

CREATE TABLE Blue (  
    id     INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
    blue   TEXT UNIQUE

)
''')
//读入刚刚建立的json数据
str_data = open('Ssq_data'+cnt+'.json',mode='r', encoding='utf-8')
json_data = json.load(str_data)
//写入数据
for entry in json_data:
    code = entry['code']
    date = entry['date']
    red = entry['red']
    blue = entry['blue']

    cur.execute('''INSERT OR IGNORE INTO Ssq (code,date,red,blue)
            VALUES ( ?,?,?,? )''', (code, date, red, blue))
    cur.execute('SELECT id FROM Ssq WHERE code = ? ', (code,))

    cur.execute('''INSERT OR IGNORE INTO DATE (date)
            VALUES ( ? )''', (date,))
    cur.execute('SELECT id FROM DATE WHERE date = ? ', (date,))

    cur.execute('''INSERT OR IGNORE INTO RE (red)
                VALUES ( ? )''', (red,))
    cur.execute('SELECT id FROM RE WHERE red = ? ', (red,))

    cur.execute('''INSERT OR IGNORE INTO Red (red)
                   VALUES ( ? )''', (red,))
    cur.execute('SELECT id FROM Red WHERE red = ? ', (red,))

    cur.execute('''INSERT OR IGNORE INTO BL (blue)
                   VALUES ( ? )''', (blue,))
    cur.execute('SELECT id FROM BL WHERE blue = ? ', (blue,))

    cur.execute('''INSERT OR IGNORE INTO Blue (blue)
                   VALUES ( ? )''', (blue,))
    cur.execute('SELECT id FROM Blue WHERE blue = ? ', (blue,))

    conn.commit()

book = xlwt.Workbook(encoding='utf-8')
sheet = book.add_sheet('双色球')//建立sheet
//建立表头
sheet.write(0, 0, '期号')
sheet.write(0, 1, '开奖日期')
sheet.write(0, 2, '红球')
sheet.write(0, 3, '蓝球')
index =1
//写入数据
for entry in json_data:
    code = entry['code']
    date = entry['date']
    red = entry['red']
    blue = entry['blue']
    sheet.write(index, 0, code)
    sheet.write(index, 1, date)
    sheet.write(index, 2, red)
    sheet.write(index, 3, blue)
    index += 1
book.save(u"Ssq_data"+cnt+".xls")//保存表格
  • 6
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值