使用 Python 爬取并打印雙色球近期 5 場開獎數據
- 前期準備
- 安裝所需庫
- 完整代碼
- 代碼解析
- 1. 導入必要的庫
- 2. 定義函數 get_recent_five_ssq
- 3. 設置請求的 URL 和 Headers
- 4. 發送請求并處理響應
- 5. 解析 HTML 內容
- 6. 提取并打印數據
- 7. 錯誤處理
首先看下運行的效果圖:
我訪問官網對比近5期的結果是沒有問題的:
我們將使用 Python 爬取并打印雙色球近期 5 場的開獎數據。這個過程涉及到網頁抓取和數據解析,利用 requests
庫來發送 HTTP 請求以獲取數據,以及 BeautifulSoup
庫來解析 HTML 內容。最終,打印出期號、日期、紅球和藍球的信息。
前期準備
安裝所需庫
首先,確保你已經安裝了 requests
和 BeautifulSoup
庫。你可以使用以下命令進行安裝:
pip install requests beautifulsoup4
完整代碼
下面是整個的完整代碼:
import requests
from bs4 import BeautifulSoupdef 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.encoding
為gbk
,以確保能正確處理網頁的編碼格式。
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
捕獲并處理請求過程中可能出現的異常。