初识python 之 爬虫:爬取双色球中奖号码信息
阅读原文时间:2023年07月09日阅读:1

**人生还是要有梦想的,毕竟还有python。比如,通过python来搞一搞彩票(双色球)。

注:此文仅用于python学习,结果仅作参考。

用到知识点:
**1、爬取网页基础数据
2、将数据写入excel文件
3、将数据统计结果可视化输出

**
主要步骤:**
  1、获取双色球网页中,中奖号码信息数据
  2、将数据放入excle(学习使用python将数据写入excel)
  3、分别将红球中奖号码、蓝球中奖号码放入两个列表中,用于后续分别统计红球、蓝球出现的中奖次数
  4、获取球出现的次数
  5、使用可视化工具以柱状图、折线图形式展示数据处理结果

详细代码如下:

#!/user/bin env python

author:Simple-Sir

time:2019/7/29 16:32

爬取双色球中奖号码数据

1、获取双色球网页中,中奖号码信息数据

2、将数据放入excle(学习使用python将数据写入excel)

3、分别将红球中奖号码、蓝球中奖号码放入两个列表中,用于后续分别统计红球、蓝球出现的中奖次数

4、获取球出现的次数

5、使用可视化工具以柱状图、折线图形式展示数据处理结果

import requests
from bs4 import BeautifulSoup
import openpyxl
from pyecharts.charts import Bar,Line # 官方已取消 pyecharts.Bar 方式导入
from pyecharts import options
from pyecharts.globals import ThemeType
from datetime import datetime
from pyecharts.datasets import register_files

获取双色球中奖号码信息

def get_data(n):
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE'
}
url = 'https://chart.cp.360.cn/kaijiang/ssq?lotId=220051&chartType=undefined&spanType=0&span={}'.format(n) # 爬取期数
respons = requests.get(url,headers=headers)
text = respons.text
soup = BeautifulSoup(text,'lxml')
tbody = soup.find_all('thead',class_="kaijiang")[0]
tbody_th = tbody.find_all('th')
# 创建一个excel文件
wb = openpyxl.Workbook() # 新建excel文件
ws = wb.active # 激活sheet,用于后续将数据写入
ws.title = '双色球中奖信息' # 指定sheet的名称

# 将“表头”写入excel中  
ws.cell(row=1,column=1,value=list(tbody\_th\[0\].stripped\_strings)\[0\])  # cell 方法给excel写入数据,row= 行,column=列,value=要写入的值  
ws.cell(row=1,column=2,value=list(tbody\_th\[1\].stripped\_strings)\[0\])  
ws.cell(row=1,column=3,value=list(tbody\_th\[-6\].stripped\_strings)\[0\])  
ws.cell(row=1,column=4,value=list(tbody\_th\[-5\].stripped\_strings)\[0\])

tbody = soup.find\_all('tbody',id="data-tab")\[0\]  
trs = tbody.find\_all('tr')  
data\_list=\[\] # 要写入excel的数据  
red\_list = \[\] # 红球  
blue\_list = \[\] # 蓝球  
for tr in trs:  
    tds = tr.find\_all('td')\[:4\]  
    blue\_list.append(list(tds\[3\].stripped\_strings)\[0\])  # 获取蓝球号码  
    tds\_text = \[\] # 中奖号码信息  
    redBall = ''  
    for index,td in enumerate(tds):  
        if index == 2:  # 红球  
            for i in list(td.stripped\_strings):  
                redBall = redBall+' '+ i  
                red\_list.append(i)  
            tds\_text.append(redBall.lstrip())  
        else:  
            tds\_text.append(list(td.stripped\_strings)\[0\])  
    data\_list.append(tds\_text)  
for i,dl in enumerate(data\_list):  
    for j,dt in enumerate(dl):  
        ws.cell(row=i+2,column=j+1,value=dt) # 将中奖号码信息写入excel中  
wb.save('双色球中奖信息.xlsx')  # 将数据保存到本地excel中  
return red\_list,blue\_list

获取球出现的次数

def count_ball(ball_list,color_list):
'''
:param ball_list: 所有中奖号码,红球+蓝球 剔重数据
:param color_list: 红球号码或蓝球号码
:return: 中奖号码出现的次数
'''
ball_dict={}
for d in ball_list:
ball_dict[d]=0
for ball in ball_list:
ball_dict[ball]=color_list.count(ball) # 获取球出现的次数
count_y = list(ball_dict.values())
return count_y

柱状图

def mkCharts(x,y1,y2,n):
bar = Bar(init_opts = options.InitOpts(theme=ThemeType.DARK)) # 对表格添加主题
bar.add_xaxis(x) # x轴:所有中奖号码,红球+蓝球
bar.add_yaxis('红球',y1)
bar.add_yaxis('蓝球', y2)
tim = datetime.now().strftime('%Y-%m-%d')
bar.set_global_opts(title_opts=options.TitleOpts(title="最近{}期双色球红蓝球中奖次数".format(n), subtitle=tim))
bar.render('双色球(柱状图).html')

折线图,使用官方主题 https://pyecharts.org/#/zh-cn/themes?id=%e4%b8%bb%e9%a2%98%e9%a3%8e%e6%a0%bc

def mkLine1(x,y1,y2,n):
tim = datetime.now().strftime('%Y-%m-%d')
line=(
Line(init_opts=options.InitOpts(theme=ThemeType.CHALK))
.add_xaxis(x)
.add_yaxis('红球', y1)
.add_yaxis('蓝球', y2)
.set_global_opts(title_opts=options.TitleOpts(title="最近{}期双色球红蓝球中奖次数".format(n),subtitle=tim))
)
line.render('双色球(折线图官方).html')

使用主题工具创建主题 https://echarts.baidu.com/theme-builder/

def mkLine2(x,y1,y2,n):
register_files({'myTheme':['/js/customed.project','json']})
tim = datetime.now().strftime('%Y-%m-%d')
line=(
# Line(init_opts=options.InitOpts(theme=ThemeType.WESTEROS))
Line(init_opts=options.InitOpts(theme="myTheme"))
.add_xaxis(x)
.add_yaxis('红球', y1)
.add_yaxis('蓝球', y2)
.set_global_opts(title_opts=options.TitleOpts(title="最近{}期双色球红蓝球中奖次数".format(n),subtitle=tim))
)
line.render('双色球(折线图自定义).html')

def main(n):
red_list = get_data(n)[0]
blue_list = get_data(n)[1]
x = sorted(set(red_list + blue_list))
y_red = count_ball(x, red_list)
y_blue = count_ball(x, blue_list)
mkCharts(x, y_red, y_blue,n) # 柱状图
mkLine1(x,y_red,y_blue,n) # 系统主题
mkLine2(x,y_red,y_blue,n) # 自定义主题

if __name__ == '__main__':
n = input('您想获取最近多少期的数据?\n')
main(n)
print('统计信息已爬取完成。')

爬取双色球中奖号码数据

执行过程:

执行结果:

excel:

 

 

柱状图:DARK

 

 折线图:官方主题样式 CHALK

 

 折线图:使用官方主题工具制作 myTheme

 

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章