当前位置: 首页 > news >正文

【Python爬虫】利用爬虫抓取双色球开奖号码,获取完整数据并通过随机森林和多层感知两种模型进行简单的预测

首先我们需要通过爬虫获取往期双色球号码并将其保存在csv文件中,这里我获取了1000期的数据,时间很久,大家可以修改代码少收集一些做尝试!

import requests
import os
from bs4 import BeautifulSoup
import csv
import timedef download(url, page):while True:try:html = requests.get(url).textsoup = BeautifulSoup(html, 'html.parser')list = soup.select('div.ball_box01 ul li')ball = []for li in list:ball.append(li.string)if not ball:raise ValueError("Empty data")write_to_excel(page, ball)print(f"第{page}期开奖结果录入完成")breakexcept Exception as e:print(f"Attempt failed with error: {e}, retrying...")time.sleep(5)  # 等待5秒后重试def write_to_excel(page, ball):with open('双色球开奖结果2.csv', 'a', encoding='utf_8_sig', newline='') as f:writer = csv.writer(f)writer.writerow([f'第{page}期'] + ball)def turn_page():url = "https://kaijiang.500.com/ssq.shtml"html = requests.get(url).textsoup = BeautifulSoup(html, 'html.parser')pageList = soup.select("div.iSelectList a")recent_pages = pageList[:1000]  # 获取最近1000期的页码for p in recent_pages:url = p['href']page = p.stringdownload(url, page)def main():if os.path.exists('双色球开奖结果2.csv'):os.remove('双色球开奖结果2.csv')turn_page()if __name__ == '__main__':main()

这里是随机森林预测

import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor# 读取数据
data = pd.read_csv('双色球开奖结果2.csv')  # ,encoding='gbk'# 提取特征和标签
features = data.iloc[:, 1:7]  # 红色球特征
labels = data.iloc[:, 1:7]  # 红色球标签
blue_balls = data.iloc[:, 7]  # 蓝色球标签# 创建随机森林回归模型
model = RandomForestRegressor(n_estimators=100, random_state=1)# 拟合模型
model.fit(features, labels)# 预测下一期的红色球号码
next_red_balls = model.predict(features.iloc[-1].values.reshape(1, -1))
next_red_balls = np.round(next_red_balls).astype(int)# 预测下一期的蓝色球号码
blue_ball_model = RandomForestRegressor(n_estimators=100, random_state=1)
blue_ball_model.fit(features, blue_balls)
next_blue_ball = blue_ball_model.predict(features.iloc[-1].values.reshape(1, -1))
next_blue_ball = np.round(next_blue_ball).astype(int)# 打印预测的红色球号码和蓝色球号码
print("预测的红色球号码:", next_red_balls)
print("预测的蓝色球号码:", next_blue_ball)

多层感知

import pandas as pd
import numpy as np
from sklearn.neural_network import MLPRegressor# 读取数据
data = pd.read_csv('双色球开奖结果2.csv')  # , encoding='gbk'# 提取特征和标签
features = data.iloc[:, 1:7]  # 红色球特征
labels = data.iloc[:, 1:8]  # 红色球标签和蓝色球标签# 创建多层感知机回归模型
model = MLPRegressor(hidden_layer_sizes=(100,), random_state=1)# 拟合模型
model.fit(features, labels)
# 预测下一期的红色球号码和蓝色球号码
next_features = model.predict(features.iloc[[-1]])
next_features = np.round(next_features).astype(int)# 打印预测的红色球号码和蓝色球号码
print("预测的红色球号码:", next_features[:6])
print("预测的蓝色球号码:", next_features[6])

 杰哥这里仅做了简单的预测,闲暇时间无聊做的,大家想要更精确的结果需要更精细的调参!

 

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • redis基本数据类型和常见命令
  • 工具使用记录-Tkinter
  • Leetcode 无重复字符的最长子串
  • slf4j依赖冲突处理
  • torchvision.transforms.ToPILImage()使用
  • MySQL 故障排查与性能优化指南
  • 韶音开放式耳机好用吗?南卡、韶音、Oladance、Cleer热门开放式耳机一周横评
  • 【Gateway】网关服务快速上手
  • uniapp数据缓存和发起网络请求
  • Unity Apple Vision Pro 开发(五):PolySpatial 2.0 导入方式
  • flink中slotSharingGroup() 的详解
  • 相亲交友程序系统开发产品分析
  • 【H2O2|全栈】关于HTML(4)HTML基础(三)
  • 掌握Go语言中的时间与日期操作
  • 影刀RPA实战:自动化批量生成条形码完整指南
  • Android 架构优化~MVP 架构改造
  • Android组件 - 收藏集 - 掘金
  • Electron入门介绍
  • java2019面试题北京
  • JavaScript中的对象个人分享
  • Mac转Windows的拯救指南
  • Material Design
  • Swift 中的尾递归和蹦床
  • Vim Clutch | 面向脚踏板编程……
  • webpack+react项目初体验——记录我的webpack环境配置
  • 表单中readonly的input等标签,禁止光标进入(focus)的几种方式
  • 如何打造100亿SDK累计覆盖量的大数据系统
  • Nginx惊现漏洞 百万网站面临“拖库”风险
  • !!【OpenCV学习】计算两幅图像的重叠区域
  • # Spring Cloud Alibaba Nacos_配置中心与服务发现(四)
  • (+4)2.2UML建模图
  • (13):Silverlight 2 数据与通信之WebRequest
  • (2022 CVPR) Unbiased Teacher v2
  • (2024,RWKV-5/6,RNN,矩阵值注意力状态,数据依赖线性插值,LoRA,多语言分词器)Eagle 和 Finch
  • (3)(3.2) MAVLink2数据包签名(安全)
  • (6)添加vue-cookie
  • (C#)获取字符编码的类
  • (C++二叉树05) 合并二叉树 二叉搜索树中的搜索 验证二叉搜索树
  • (day 12)JavaScript学习笔记(数组3)
  • (PWM呼吸灯)合泰开发板HT66F2390-----点灯大师
  • (备份) esp32 GPIO
  • (附源码)spring boot球鞋文化交流论坛 毕业设计 141436
  • (附源码)springboot 基于HTML5的个人网页的网站设计与实现 毕业设计 031623
  • (论文阅读31/100)Stacked hourglass networks for human pose estimation
  • (七)理解angular中的module和injector,即依赖注入
  • (收藏)Git和Repo扫盲——如何取得Android源代码
  • (一)Kafka 安全之使用 SASL 进行身份验证 —— JAAS 配置、SASL 配置
  • (转)iOS字体
  • **登录+JWT+异常处理+拦截器+ThreadLocal-开发思想与代码实现**
  • .FileZilla的使用和主动模式被动模式介绍
  • .form文件_一篇文章学会文件上传
  • .NET C# 操作Neo4j图数据库
  • .Net IE10 _doPostBack 未定义
  • .NET 设计模式—简单工厂(Simple Factory Pattern)
  • .NET精简框架的“无法找到资源程序集”异常释疑