请求头:https://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?
载荷:
params = {
"name": "ssq",
"issueCount": "",
"issueStart": "",
"issueEnd": "",
"dayStart": "",
"dayEnd": "",
"pageNo": "1",
"pageSize": "30",
"week": "",
"systemType": "PC"
}
按期数查询,issueCount,最近1000期即1000
按期号查询,issueStart,issueEnd。比如2020001-2024001
按日期查询,dayStart,dayEnd,比如2020-01-01到2024-01-01
可以自定义输入,也可写好在参数里,另外添加标头和cookies自行添加
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
"cookie": ""
}
响应是json
def fetch_data(url, params):
try:
response = requests.get(url, headers=header, params=params)
response.raise_for_status() # Raises HTTPError for bad responses (4xx and 5xx)
response.encoding = 'utf-8'
return response.json()
except requests.RequestException as e:
print(f"请求发生错误: {e}")
return None
except json.JSONDecodeError:
print("无法解码 JSON 数据")
return None
获取响应中的页数用来作请求的次数
# 获取数据
res = fetch_data(url, params)
if res is None:
exit()
pagenum = res.get("pageNum", 0)
print(f"总页数: {pagenum}")
data = []
for i in range(1, int(pagenum) + 1):
params["pageNo"] = str(i)
jsondata = fetch_data(url, params)
if jsondata is None or "result" not in jsondata:
continue
for result in jsondata["result"]:
code = result["code"]
red = result["red"].split(',')
blue = result["blue"]
date = result["date"]
week = result["week"]
print(f"期数:{code} 红球:{red} 蓝球:{blue} 日期:{date} 星期:{week}")
data.append([code, date, week] + red + [blue])
保存到excel
# 创建 DataFrame
columns = ["期数", "日期", "星期", "红球号码1", "红球号码2", "红球号码3", "红球号码4", "红球号码5", "红球号码6", "蓝球号码"]
df = pd.DataFrame(data, columns=columns)
output_path = "双色球结果和统计.xlsx"
# 保存开奖结果
try:
book = load_workbook(output_path)
with pd.ExcelWriter(output_path, engine='openpyxl', mode='a', if_sheet_exists='replace') as writer:
writer.book = book
writer.sheets = {ws.title: ws for ws in book.worksheets}
df.to_excel(writer, sheet_name="开奖结果", index=False)
except FileNotFoundError:
df.to_excel(output_path, sheet_name="开奖结果", index=False)
except InvalidFileException:
df.to_excel(output_path, sheet_name="开奖结果", index=False)
print(f"开奖结果已保存到 {output_path}")
完整代码,运行生成红球和蓝球的热力图,分布图及excel表格,需要自己去网站链接复制一个cookies如果需要
import requests
import json
import pandas as pd
from openpyxl import load_workbook
from openpyxl.utils.exceptions import InvalidFileException
from openpyxl.styles import PatternFill
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.font_manager as fm
import random
# Configuration
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
"cookie": ""
}
url = "https://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?"
# 获取用户输入的查询参数
query_type = input("1: 按期数查询\n2: 按期号查询\n3: 按日期查询\n请选择查询方式:")
params = {
"name": "ssq",
"issueCount": "",
"issueStart": "",
"issueEnd": "",
"dayStart": "",
"dayEnd": "",
"pageNo": "1",
"pageSize": "30",
"week": "",
"systemType": "PC"
}
if query_type == '1':
params["issueCount"] = input("最近100期即100\n请输入期数:")
elif query_type == '2':
params["issueStart"] = input("请输入起始期号:")
params["issueEnd"] = input("请输入结束期号:")
elif query_type == '3':
params["dayStart"] = input("请输入起始日期(格式:YYYY-MM-DD):")
params["dayEnd"] = input("请输入结束日期(格式:YYYY-MM-DD):")
else:
print("无效的选择")
exit()
def fetch_data(url, params):
try:
response = requests.get(url, headers=header, params=params)
response.raise_for_status() # Raises HTTPError for bad responses (4xx and 5xx)
response.encoding = 'utf-8'
return response.json()
except requests.RequestException as e:
print(f"请求发生错误: {e}")
return None
except json.JSONDecodeError:
print("无法解码 JSON 数据")
return None
# 获取数据
res = fetch_data(url, params)
if res is None:
exit()
pagenum = res.get("pageNum", 0)
print(f"总页数: {pagenum}")
data = []
for i in range(1, int(pagenum) + 1):
params["pageNo"] = str(i)
jsondata = fetch_data(url, params)
if jsondata is None or "result" not in jsondata:
continue
for result in jsondata["result"]:
code = result["code"]
red = result["red"].split(',')
blue = result["blue"]
date = result["date"]
week = result["week"]
print(f"期数:{code} 红球:{red} 蓝球:{blue} 日期:{date} 星期:{week}")
data.append([code, date, week] + red + [blue])
# 创建 DataFrame
columns = ["期数", "日期", "星期", "红球号码1", "红球号码2", "红球号码3", "红球号码4", "红球号码5", "红球号码6", "蓝球号码"]
df = pd.DataFrame(data, columns=columns)
output_path = "双色球结果和统计.xlsx"
# 保存开奖结果
try:
book = load_workbook(output_path)
with pd.ExcelWriter(output_path, engine='openpyxl', mode='a', if_sheet_exists='replace') as writer:
writer.book = book
writer.sheets = {ws.title: ws for ws in book.worksheets}
df.to_excel(writer, sheet_name="开奖结果", index=False)
except FileNotFoundError:
df.to_excel(output_path, sheet_name="开奖结果", index=False)
except InvalidFileException:
df.to_excel(output_path, sheet_name="开奖结果", index=False)
print(f"开奖结果已保存到 {output_path}")
# Step 2: 统计和保存结果到一个 Excel 文件中的单个工作表
try:
df = pd.read_excel(output_path, sheet_name="开奖结果")
except Exception as e:
print(f"读取文件时发生错误: {e}")
exit()
# 初始化统计字典
red_counts = {str(i): {f"位置{j+1}": 0 for j in range(6)} for i in range(1, 34)}
blue_counts = {str(i): 0 for i in range(1, 17)}
# 初始化星期二、四、日统计字典
weekdays = {"星期二": "二", "星期四": "四", "星期日": "日"}
red_counts_week = {day: {str(i): {f"位置{j+1}": 0 for j in range(6)} for i in range(1, 34)} for day in weekdays.values()}
blue_counts_week = {day: {str(i): 0 for i in range(1, 17)} for day in weekdays.values()}
# 统计每个数字的出现次数
for index, row in df.iterrows():
red_numbers = row[3:9].dropna().astype(int)
blue_number = row[9]
week = row[2]
for j, num in enumerate(red_numbers):
num_str = str(num).strip()
if num_str in red_counts:
red_counts[num_str][f"位置{j+1}"] += 1
if week in weekdays.values():
if num_str in red_counts_week[week]:
red_counts_week[week][num_str][f"位置{j+1}"] += 1
blue_number_str = str(blue_number).strip()
if blue_number_str in blue_counts:
blue_counts[blue_number_str] += 1
if week in weekdays.values():
if blue_number_str in blue_counts_week[week]:
blue_counts_week[week][blue_number_str] += 1
# 计算总期数
total_periods = len(df)
if total_periods == 0:
print("数据为空,没有统计结果。")
exit()
# 计算每个数字的概率并将其保存到 DataFrame
red_data = []
for num, counts in red_counts.items():
row = {"号码": num}
for pos, count in counts.items():
row[f"{pos}次"] = count
row[f"{pos}概率"] = count / total_periods
red_data.append(row)
blue_data = []
for num, count in blue_counts.items():
row = {"号码": num, "蓝球次数": count, "蓝球概率": count / total_periods}
blue_data.append(row)
# 计算星期二、四、日的统计
red_data_week = {day: [] for day in weekdays.values()}
blue_data_week = {day: [] for day in weekdays.values()}
for day in weekdays.values():
total_periods_week = len(df[df["星期"] == day])
for num, counts in red_counts_week[day].items():
row = {"号码": num}
for pos, count in counts.items():
row[f"{pos}次(星期{day})"] = count
row[f"{pos}概率(星期{day})"] = count / total_periods_week
red_data_week[day].append(row)
for num, count in blue_counts_week[day].items():
row = {"号码": num, f"蓝球次数(星期{day})": count, f"蓝球概率(星期{day})": count / total_periods_week}
blue_data_week[day].append(row)
# 合并红球和蓝球数据
for red in red_data:
num = red["号码"]
for blue in blue_data:
if blue["号码"] == num:
red["蓝球次数"] = blue["蓝球次数"]
red["蓝球概率"] = blue["蓝球概率"]
break
else:
red["蓝球次数"] = 0
red["蓝球概率"] = 0.0
# 合并星期二、四、日的红球和蓝球数据
for day in weekdays.values():
for red in red_data_week[day]:
num = red["号码"]
for blue in blue_data_week[day]:
if blue["号码"] == num:
red[f"蓝球次数(星期{day})"] = blue[f"蓝球次数(星期{day})"]
red[f"蓝球概率(星期{day})"] = blue[f"蓝球概率(星期{day})"]
break
else:
red[f"蓝球次数(星期{day})"] = 0
red[f"蓝球概率(星期{day})"] = 0.0
red_counts_df = pd.DataFrame(red_data)
red_counts_week_dfs = {day: pd.DataFrame(data) for day, data in red_data_week.items()}
# 保存结果到新的 Excel 文件中的统计结果sheet
try:
with pd.ExcelWriter(output_path, engine='openpyxl', mode='a', if_sheet_exists='replace') as writer:
red_counts_df.to_excel(writer, sheet_name="统计结果", index=False)
for day, df in red_counts_week_dfs.items():
df.to_excel(writer, sheet_name=f"星期{day}统计结果", index=False)
print(f"统计结果已保存到 {output_path}")
except Exception as e:
print(f"保存文件时发生错误: {e}")
# 加载保存后的Excel文件,进行高亮处理
try:
book = load_workbook(output_path)
sheet = book["统计结果"]
yellow_fill = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
red_fill = PatternFill(start_color="FF0000", end_color="FF0000", fill_type="solid")
for col in range(3, 12, 2): # 概率列
values = [cell[0].value for cell in sheet.iter_cols(min_row=2, min_col=col, max_col=col, values_only=True)]
if not values: # 如果没有值,继续下一列
continue
max_value = max(values)
min_value = min(values)
for cell in sheet.iter_cols(min_row=2, min_col=col, max_col=col):
for c in cell:
if c.value == max_value:
c.fill = red_fill
elif c.value == min_value:
c.fill = yellow_fill
# 保存带有高亮的Excel文件
book.save(output_path)
print(f"高亮处理已完成并保存到 {output_path}")
except Exception as e:
print(f"高亮处理时发生错误: {e}")
# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 正常显示负号
# 创建红球号码出现频率的热力图
red_heatmap_data = pd.DataFrame(red_counts).T.astype(int)
plt.figure(figsize=(12, 8))
sns.heatmap(red_heatmap_data, annot=True, fmt="d", cmap="YlGnBu")
plt.title('红球号码热力图')
plt.savefig('红球号码出现频率热力图.png') # 自动保存图表
#plt.show()
plt.close()
# 创建蓝球号码出现频率的热力图
blue_heatmap_data = pd.DataFrame.from_dict(blue_counts, orient='index', columns=['次数']).astype(int)
plt.figure(figsize=(8, 6))
sns.heatmap(blue_heatmap_data.T, annot=True, fmt="d", cmap="YlGnBu")
plt.title('蓝球号码热力图')
plt.savefig('蓝球号码出现频率热力图.png') # 自动保存图表
#plt.show()
plt.close()
# 创建红球号码出现频率的分布图
red_numbers_total_counts = {str(i): 0 for i in range(1, 34)}
for num, pos_counts in red_counts.items():
for pos, count in pos_counts.items():
red_numbers_total_counts[num] += count
red_numbers_series = pd.Series(red_numbers_total_counts).sort_index().astype(int)
plt.figure(figsize=(12, 8))
sns.barplot(x=red_numbers_series.index, y=red_numbers_series.values)
plt.title('红球号码分布')
plt.xlabel('号码')
plt.ylabel('频率')
plt.savefig('红球号码分布.png') # 自动保存图表
plt.close()
# 创建蓝球号码出现频率的分布图
blue_numbers_series = pd.Series(blue_counts).sort_index().astype(int)
plt.figure(figsize=(8, 6))
sns.barplot(x=blue_numbers_series.index, y=blue_numbers_series.values)
plt.title('蓝球号码分布')
plt.xlabel('号码')
plt.ylabel('频率')
plt.savefig('蓝球号码分布.png') # 自动保存图表
plt.close()
# 生成推荐号码组合
def generate_recommendations(red_counts, blue_counts, n=5):
recommendations = []
red_nums = list(red_counts.keys())
blue_nums = list(blue_counts.keys())
for _ in range(n):
red_comb = random.sample(red_nums, 6)
blue_comb = random.choice(blue_nums)
recommendations.append((sorted(red_comb), blue_comb))
return recommendations
# 根据统计数据生成推荐号码组合
recommendations = generate_recommendations(red_counts, blue_counts)
print("推荐号码组合:")
for red_comb, blue_comb in recommendations:
print(f"红球: {red_comb}, 蓝球: {blue_comb}")