使用python爬取双色球开奖结果并预测
爬取双色球开奖结果
import requests
import os
from bs4 import BeautifulSoup
def download(url, page):
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')
list = soup.select('div.ball_box01 ul li')
ball = []
for li in list:
ball.append(li.string)
write_to_excel(page, ball)
print(f"第{page}期开奖结果录入完成")
def write_to_excel(page, ball):
f = open('双色球开奖结果.csv', 'a', encoding='utf_8_sig')
f.write(f'第{page}期,{ball[0]},{ball[1]},{ball[2]},{ball[3]},{ball[4]},{ball[5]},{ball[6]}\n')
f.close()
def turn_page():
url = "https://kaijiang.500.com/dlt.shtml"
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')
pageList = soup.select("div.iSelectList a")
recent_pages = pageList[:30]
for p in recent_pages:
url = p['href']
page = p.string
download(url, page)
def main():
if os.path.exists('双色球开奖结果.csv'):
os.remove('双色球开奖结果.csv')
turn_page()
if __name__ == '__main__':
main()
读取爬取数据并使用多层感知机回归模型预测红球结果
import pandas as pd
import numpy as np
from sklearn.neural_network import MLPRegressor
data = pd.read_csv('双色球开奖结果.csv')
features = data.iloc[:, 1:7]
labels = data.iloc[:, 1:7]
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)
读取爬取数据并使用随机森林回归模型预测红球结果
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestRegressor
data = pd.read_csv('双色球开奖结果.csv')
features = data.iloc[:, 1:7]
labels = data.iloc[:, 1:7]
model = RandomForestRegressor(n_estimators=100, random_state=1)
model.fit(features, labels)
next_features = model.predict(features.iloc[-1].values.reshape(1, -1))
next_features = np.round(next_features).astype(int)
print("预测的红色球号码:", next_features)
使用随机数进行随机生成大乐透和双色球号码
import random
def generate_double_color_ball():
red_balls = random.sample(range(1, 33), 6)
red_balls.sort()
blue_ball = random.randint(1, 16)
return red_balls, blue_ball
def generate_lotto():
red_balls = random.sample(range(1, 35), 5)
red_balls.sort()
blue_balls = random.sample(range(1, 12), 2)
blue_balls.sort()
return red_balls, blue_balls
red_balls, blue_ball = generate_double_color_ball()
print("双色球号码:")
print("红色球号码:", red_balls)
print("蓝色球号码:", blue_ball)
red_balls, blue_balls = generate_lotto()
print("大乐透号码:")
print("红色球号码:", red_balls)
print("蓝色球号码:", blue_balls)
运行结果
![爬取结果成功](https://img-blog.csdnimg.cn/direct/49466a23ed084c72baeb19367e25bd72.png)
![预测结果](https://img-blog.csdnimg.cn/direct/575b1e00f6b54bce9d8894259b42328e.png)
![随机生成号码](https://img-blog.csdnimg.cn/direct/066b4df969ba4510b75d6e06f9927e24.png)