手把手教你利用python代码快速获取双色球历史数据(附源码)
一、windows安装python环境
1、打开浏览器,在搜索框中输入Python,进入到Python的官网中。
2、在Python官网中进入Downloads菜单栏,我们选择windows版本
3、下载对应的Python安装包
4、找到下载的Python包,双击安装
5、cmd命令验证是否安装成功
至此,Python安装完成
6、安装Python依赖库
cmd直接运行命令pip install requests beautifulsoup4 openpyxl
二、编写代码
1、桌面新建文件夹test,文件夹内新建文件test.py。
2、复制代码到test.py中(代码私信获取)
import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook
import concurrent.futures
import re
import time
import random
# 初始化工作簿
wb = Workbook()
ws = wb.active
ws.append(['期号', '开奖日期', '红球1', '红球2', '红球3', '红球4', '红球5', '红球6', '蓝球'])
# 配置中心(动态适配)
CONFIG = {
'BASE_URL': 'https://kaijiang.zhcw.com/zhcw/html/ssq/list_%d.html',
'HEADERS': {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Connection': 'keep-alive'
},
'MAX_WORKERS': 20,
'RETRIES': 3,
'DELAY_RANGE': (0.1, 0.3),
'PAGINATION_SELECTORS': [
'p.pg',
'div.pagination',
'nav.pagination'
],
'PAGE_PATTERN': re.compile(r'pageNum=(\d+)'),
'TABLE_SELECTORS': [
'table.wqhgt',
'table.lottery-table'
]
}
def get_valid_pages():
"""智能分页解析(动态适配不同网页结构)"""
try:
response = requests.get(CONFIG['BASE_URL'] % 1, headers=CONFIG['HEADERS'], timeout=10)
print(f"请求状态码: {response.status_code}")
print(f"请求内容(前500字符): {response.text[:500]}")
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# 尝试所有分页选择器
pagination = None
for selector in CONFIG['PAGINATION_SELECTORS']:
pagination = soup.select_one(selector)
if pagination:
print(f"找到分页区域,选择器为: {selector}")
print(f"分页区域完整HTML内容: {pagination.prettify()}")
break
if not pagination:
print("未找到分页区域,默认返回1页")
return [1]
# 提取总页数
total_pages_text = pagination.find_all('strong')[0].get_text(strip=True)
try:
total_pages = int(total_pages_text)
except ValueError:
print("无法提取总页数,默认返回1页")
return [1]
# 生成完整的页码列表
pages = list(range(1, total_pages + 1))
print(f"生成完整页码列表: {pages}")
return pages
except Exception as e:
print(f"分页解析错误: {str(e)}")
return [1]
def download_page(page):
"""带智能重试的页面下载"""
url = f'https://kaijiang.zhcw.com/zhcw/inc/ssq/ssq_wqhg.jsp?pageNum={page}'
for retry in range(CONFIG['RETRIES']):
try:
time.sleep(random.uniform(*CONFIG['DELAY_RANGE']))
response = requests.get(url, headers=CONFIG['HEADERS'], timeout=10)
print(f"页面 {page} 请求状态码: {response.status_code}")
print(f"页面 {page} 请求内容(前500字符): {response.text[:500]}")
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
table = None
for selector in CONFIG['TABLE_SELECTORS']:
table = soup.select_one(selector)
if table:
print(f"页面 {page} 找到表格,选择器为: {selector}")
break
if not table:
# 打印所有表格,辅助定位
all_tables = soup.find_all('table')
print(f"页面 {page} 未找到表格数据,页面上共有 {len(all_tables)} 个表格:")
for idx, tbl in enumerate(all_tables):
print(f"表格 {idx + 1} 内容(前200字符): {tbl.text[:200]}")
return []
return parse_table(table)
except Exception as e:
print(f"页面 {page} 重试 {retry + 1}/{CONFIG['RETRIES']}: {str(e)}")
return []
def parse_table(table):
"""鲁棒的数据解析(处理结构变化)"""
data = []
for row in table.find_all('tr')[1:]:
tds = row.find_all('td')
if len(tds) < 3:
continue
try:
cells = [td.get_text(strip=True) for td in tds[:3]]
if len(cells) < 3:
continue
issue, date = auto_detect_issue_date(cells)
balls = []
# 尝试不同的球号提取方式
em_tags = tds[2].find_all('em')
if em_tags:
balls = [em.get_text(strip=True) for em in em_tags]
else:
balls = cells[2].split()
if len(balls) == 7:
data.append([issue, date] + balls[:6] + [balls[6]])
except Exception as e:
print(f"行解析错误: {str(e)}")
return data
def auto_detect_issue_date(cells):
"""智能检测期号和日期(处理列顺序变化)"""
for i, cell in enumerate(cells):
if re.match(r'\d{4}-\d{2}-\d{2}', cell):
date = cell
issue = cells[(i + 1) % 3]
return issue, date
return cells[0], cells[1]
def main():
start_time = time.time()
total_rows = 0
all_data = []
# 智能分页解析(支持结构变化)
pages = get_valid_pages()
total_pages = max(pages) if pages else 1
print(f"检测到有效页数: {total_pages} 页,具体页码: {pages}")
# 并发下载(线程池)
with concurrent.futures.ThreadPoolExecutor(max_workers=CONFIG['MAX_WORKERS']) as executor:
futures = {executor.submit(download_page, page): page for page in pages}
for future in concurrent.futures.as_completed(futures):
data = future.result()
all_data.extend(data)
for row in data:
total_rows += 1
print(f"页面 {futures[future]} 完成: {len(data)} 条")
# 按日期降序排序
all_data.sort(key=lambda x: x[1], reverse=True)
# 将排序后的数据写入 Excel
for row in all_data:
ws.append(row)
# 保存文件
try:
wb.save('双色球历史数据.xlsx')
print(f"\n操作完成!共获取 {total_rows} 条数据(表头1行)")
except PermissionError:
print("错误:请关闭已打开的Excel文件后重试")
finally:
wb.close()
# 性能报告
if time.time() - start_time > 0:
print(f"耗时: {time.time() - start_time:.2f} 秒 | 速度: {total_rows / (time.time() - start_time):.1f} 条/秒")
else:
print("耗时过短,无法计算速度。")
if __name__ == '__main__':
main()
3、右击桌面test文件夹,选择在终端中打开。
4、运行命令python test.py,几秒钟后会在test文件夹中生成一个名为“双色球历史数据.xlsx”的文件,即为爬到的双色球历史数据,
三、总结
1、该代码生成的 Excel 文件中的数据将按日期降序排列。
2、大大缩短时间,并发下载。提高效率。
3、动态适配页面。
4、防止反爬。
作者观点:好多网友认为获取到这个数据没什么意义。能获取到本期未开奖的号码才是牛逼。个人认为获取这个数据:1 是让大家了解下python爬虫的技术,可以慢慢掌握这个技能,举一反三,在生活学习中提高工作效率。2 是个人认为双色球是一个统计学,不是概率学,什么是统计学,就是哪组号码买的人少,主任开哪组,并不是有了这些数据,根据哪些号码长期没开,下次就一定会开,每期开奖的号码都是一次独立性事件,上次的开奖结果并不会影响下期的开奖号码。最后,祝大家好运,好好学习python技术。人人中大奖。