使用 Python 爬取并打印双色球近期 5 场开奖数据

首先看下运行的效果图:
在这里插入图片描述
我访问官网对比近5期的结果是没有问题的:
在这里插入图片描述

我们将使用 Python 爬取并打印双色球近期 5 场的开奖数据。这个过程涉及到网页抓取和数据解析,利用 requests 库来发送 HTTP 请求以获取数据,以及 BeautifulSoup 库来解析 HTML 内容。最终,打印出期号、日期、红球和蓝球的信息。

前期准备

安装所需库

首先,确保你已经安装了 requestsBeautifulSoup 库。你可以使用以下命令进行安装:

pip install requests beautifulsoup4

完整代码

下面是整个的完整代码:

import requests
from bs4 import BeautifulSoup

def get_recent_five_ssq():
    # 目标URL,用于获取最新的开奖信息
    url = "https://datachart.500.com/ssq/history/newinc/history.php?start=00001&end=99999"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
    }

    try:
        # 发送请求获取网页内容
        response = requests.get(url, headers=headers)
        response.encoding = 'gbk'  # 设置正确的编码方式
        response.raise_for_status()

        # 解析网页内容
        soup = BeautifulSoup(response.text, 'html.parser')
        table = soup.find('tbody', {'id': 'tdata'})

        if not table:
            print("无法找到开奖数据表格,可能是网页结构发生变化。")
            return

        # 提取最新的5场开奖数据
        recent_five = table.find_all('tr')[:5]  # 取前5行数据

        # 打印开奖结果
        for row in recent_five:
            cols = row.find_all('td')
            issue = cols[0].text.strip()
            date = cols[15].text.strip()
            red_balls = [cols[i].text.strip() for i in range(1, 7)]
            blue_ball = cols[7].text.strip()

            print(f"期号: {issue}, 日期: {date}, 红球: {', '.join(red_balls)}, 蓝球: {blue_ball}")

    except requests.RequestException as e:
        print(f"请求错误: {e}")

# 执行函数
get_recent_five_ssq()

代码解析

1. 导入必要的库

import requests
from bs4 import BeautifulSoup

这两行代码导入我们将要使用的库。 requests 用于发送 HTTP 请求,而 BeautifulSoup 用于解析 HTML 内容。

2. 定义函数 get_recent_five_ssq

def get_recent_five_ssq():

我们定义了一个函数 get_recent_five_ssq 来封装获取并打印双色球开奖数据的操作。

3. 设置请求的 URL 和 Headers

url = "https://datachart.500.com/ssq/history/newinc/history.php?start=00001&end=99999"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
}
  • URL : 指向 500 彩票的双色球历史开奖信息页面。
  • Headers : 设置请求的 User-Agent ,模拟浏览器请求以避免被服务器拒绝。

4. 发送请求并处理响应

response = requests.get(url, headers=headers)
response.encoding = 'gbk'  # 设置正确的编码方式
response.raise_for_status()
  • 使用 requests.get 发送 GET 请求。
  • 设置 response.encodinggbk ,以确保能正确处理网页的编码格式。

5. 解析 HTML 内容

soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('tbody', {'id': 'tdata'})
  • 通过 BeautifulSoup 解析 HTML 内容。
  • 使用 soup.find 找到包含开奖数据的表格。

6. 提取并打印数据

recent_five = table.find_all('tr')[:5]  # 取前5行数据
for row in recent_five:
    cols = row.find_all('td')
    issue = cols[0].text.strip()
    date = cols[15].text.strip()
    red_balls = [cols[i].text.strip() for i in range(1, 7)]
    blue_ball = cols[7].text.strip()

    print(f"期号: {issue}, 日期: {date}, 红球: {', '.join(red_balls)}, 蓝球: {blue_ball}")
  • 提取最新的 5 场开奖数据。
  • 遍历每行数据,并提取期号、日期、红球和蓝球的信息。
  • 使用 print 函数打印每场开奖的结果。

7. 错误处理

except requests.RequestException as e:
    print(f"请求错误: {e}")
  • 使用 try/except 捕获并处理请求过程中可能出现的异常。
Python爬取双色球历史数据通常涉及网络抓取技术,尤其是使用一些常用的库如`requests`、`BeautifulSoup`或`Scrapy`等。以下是一个简单的步骤概述: 1. **确定数据来源**:首先,你需要找到提供双色球历史开奖结果的网站,比如中国福利彩票官方网站或其他可靠的第三方彩票数据分析平台。 2. **分析网页结构**:查看目标页面的HTML源码,理解数据是如何组织的。查找包含历史开奖结果的元素,这通常是表格或列表形式的数据。 3. **编写代码**: - 使用`requests.get(url)`获取网页内容。 - 使用`BeautifulSoup`解析HTML,定位到含有历史数据的部分。 - 可能需要遍历并提取每个开奖日期、红球号码和蓝球号码的信息。 4. **数据存储**:将爬取数据保存下来,可以选择CSV、JSON、数据库等格式,便于后续处理和分析。 5. **异常处理**:考虑到网络不稳定、反爬虫策略等问题,记得添加适当的错误处理和延迟机制。 ```python import requests from bs4 import BeautifulSoup def scrape_lottery_data(url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 位置可能会因网站结构变化而变化,这里假设是class="history-data" data_rows = soup.find_all('div', class_='history-data') for row in data_rows: date = row.find('span', class_='date').text red_balls = [ball.text for ball in row.find_all('span', class_='red-ball')] blue_ball = row.find('span', class_='blue-ball').text # 存储数据 save_data(date, red_balls, blue_ball) # 定义保存数据的函数 def save_data(date, red_balls, blue_ball): # 这里只是示例,实际操作可能需要连接数据库或写入文件 with open('lottery_data.csv', 'a', newline='', encoding='utf-8') as file: writer = csv.writer(file) writer.writerow([date] + red_balls + [blue_ball]) # 调用函数开始爬取 scrape_lottery_data('http://example.com/history-draws') # 替换为你找到的历史数据URL ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

挣扎的蓝藻

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值