Python爬虫实战:福彩双色球历史数据获取步骤与示例代码全解析

以下是使用Python爬虫获取福彩历史数据的步骤和示例代码。以中国福彩双色球历史数据为例,假设目标数据可通过官方网站或第三方公开数据接口获取。

步骤 1:分析目标数据源

假设目标数据来自中国福彩官网或第三方数据网站(如500彩票网),需检查:

1. 网站是否有反爬机制(如IP限制、验证码)。

2. 数据是否通过HTML直接渲染或动态加载(如Ajax请求)。

3. 确认robots.txt是否允许爬取(如
https://www.500.com/robots.txt)。

步骤 2:获取数据接口

通过浏览器开发者工具(Network选项卡)分析数据加载方式。若数据通过Ajax接口返回JSON,则直接调用API更高效。例如,500彩票网的双色球历史数据接口可能类似:

Python爬虫实战:福彩双色球历史数据获取步骤与示例代码全解析

示例代码(静态页面爬取)

若数据在静态HTML表格中,使用requests和BeautifulSoup解析。

python

import requests

from bs4 import BeautifulSoup

import csv

import time

# 配置请求头和目标URL

headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'

}

def fetch_data(page):

url = f'https://www.500.com/ssq/list?page={page}'

response = requests.get(url, headers=headers)

if response.status_code == 200:

return response.text

else:

print(f"请求失败,状态码:{response.status_code}")

return None

def parse_html(html):

soup = BeautifulSoup(html, 'html.parser')

table = soup.find('table', {'class': 'kj-table'})

if not table:

return []

rows = table.find_all('tr')[1:] # 跳过表头

data = []

for row in rows:

cols = row.find_all('td')

if len(cols) < 10:

continue

period = cols[0].text.strip()

date = cols[1].text.strip()

red_balls = [col.text.strip() for col in cols[2:8]]

blue_ball = cols[8].text.strip()

data.append([period, date] + red_balls + [blue_ball])

return data

def save_to_csv(data, filename='ssq_history.csv'):

with open(filename, 'a', newline='', encoding='utf-8') as f:

writer = csv.writer(f)

if f.tell() == 0: # 写入表头

writer.writerow(['期号', '开奖日期', '红球1', '红球2', '红球3', '红球4', '红球5', '红球6', '蓝球'])

writer.writerows(data)

# 分页爬取

for page in range(1, 10): # 假设爬取前10页

html = fetch_data(page)

if html:

page_data = parse_html(html)

if page_data:

save_to_csv(page_data)

print(f"第{page}页数据已保存")

time.sleep(2) # 降低请求频率

print("数据爬取完成!")

示例代码(动态API接口)

若数据通过Ajax接口返回JSON:

python

import requests

import json

import pandas as pd

url = 'https://api.500.com/ssq/history'

params = {

'format': 'json',

'page': 1,

'size': 30 # 每页数据量

}

all_data = []

for page in range(1, 10):

params['page'] = page

response = requests.get(url, params=params, headers=headers)

if response.status_code == 200:

data = response.json()

all_data.extend(data['results'])

time.sleep(1)

# 转换为DataFrame并保存

df = pd.DataFrame(all_data)

df.to_csv('ssq_api_data.csv', index=False)

注意事项

1. 合法合规:确保遵守目标网站的robots.txt和服务条款,避免高频访问。

2. 反爬策略:

o 使用随机User-Agent(可借助fake_useragent库)。

o 设置请求间隔(如time.sleep(2))。

o 使用代理IP池(如requests结合proxies参数)。

3. 异常处理:增加try-except块处理网络错误或数据解析失败。

4. 数据清洗:检查数据完整性(如缺失值、格式错误)。

扩展建议

• 数据存储:可改用数据库(如SQLite、MySQL)长期存储。

• 定时任务:使用APScheduler或crontab定期更新数据。

• 可视化:用matplotlib或pandas分析历史趋势。

举报