使用 Python 擷取 juicestore.tw 的球鞋資料
1. 引言
在當今的資料驅動時代,電商平台的資訊往往能夠反映市場流行趨勢與消費者行為。juicestore.tw 作為一家主打服飾與球鞋的電商平台,網站上包含了豐富的球鞋產品資訊,例如產品名稱、價格、庫存、型號等。本文的主要目標是介紹如何利用 Python 編寫爬蟲腳本,實現對 juicestore.tw 上球鞋資料的擷取,為後續的資料分析、市場調研或庫存監控提供數據支援。
在文章過程中,我們將詳細解釋每一步的實作原理與關鍵技術點,同時提醒讀者在進行資料擷取時務必遵循網站的爬蟲協議(robots.txt),尊重網站資料使用規則,避免引發不必要的法律與道德問題。
2. 準備工作
2.1 環境與工具選擇
本專案推薦使用 Python 語言。Python 擁有豐富的第三方套件與活躍的社群支援,能輕鬆應對網路請求、網頁解析與資料處理任務。
requests:用於發送 HTTP 請求,取得頁面的 HTML 資料。
BeautifulSoup(或 lxml):用於解析 HTML 頁面,擷取所需資料。
pandas:用於資料清理、處理與儲存,方便後續分析。
若需大量擷取資料,可進一步了解 Scrapy 或非同步請求庫 aiohttp。
此外,也推薦使用對應的 API 來擷取資料,例如 Luckdata 的 Sneaker API。Luckdata 整合了包含 juicestore 在內的二十多個球鞋電商介面,提供統一且結構化的資料存取方式。
以下是透過 API 擷取 juicestore 商品資料的程式碼範例:
import requestsheaders = {
'X-Luckdata-Api-Key': 'your_key'
}
response = requests.get(
'https://luckdata.io/api/sneaker-API/get_peqs?url=https://www.juicestore.tw/products/%E3%80%90salomon%E3%80%91acs-pro-desert-1',
headers=headers
)
data = response.json()
print(data)
2.2 法律與倫理提醒
遵循協議:擷取資料前,請檢查目標網站的 robots.txt 檔案,確保擷取內容在允許範圍內。
降低擷取頻率:透過合理的延遲設定,避免對網站伺服器造成過大負載。
合法使用資料:擷取資料僅供學習與技術研究之用,請勿用於商業用途或侵犯版權。
3. 資料擷取流程
本文以簡單示例說明如何擷取球鞋資料,整體流程分為:確認目標頁面、發送請求、解析 HTML 資料、資料清理與儲存四個部分。
3.1 確認目標頁面
首先,透過瀏覽器開發者工具(F12)查看 juicestore.tw 的 HTML 結構,找到包含球鞋資料的標籤。通常球鞋資訊會顯示在列表頁中,例如每個產品資訊包含於 <div class="sneaker-item">
標籤內,內含名稱與價格等欄位。
3.2 發送 HTTP 請求
使用 requests
套件向目標 URL 發送 GET 請求,獲取 HTML 內容。建議設定合適的 Header 模擬真實瀏覽器,避免被網站封鎖。
import requestsurl = "https://juicestore.tw/sneakers"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
html_content = response.text
print("成功取得頁面資料!")
else:
print("請求失敗,狀態碼:", response.status_code)
3.3 解析 HTML 資料
取得 HTML 資料後,使用 BeautifulSoup
解析頁面,根據開發者工具定位到的標籤與類別名稱擷取資料。假設每雙球鞋資訊在 <div class="sneaker-item">
內,我們可以擷取名稱與價格等欄位。
from bs4 import BeautifulSoupsoup = BeautifulSoup(html_content, 'html.parser')
items = soup.find_all("div", class_="sneaker-item")
sneakers_data = []
for item in items:
title = item.find("h2").get_text(strip=True) if item.find("h2") else "無名稱"
price = item.find("span", class_="price").get_text(strip=True) if item.find("span", class_="price") else "無價格"
sneakers_data.append({
"title": title,
"price": price
})
print(sneakers_data)
3.4 資料清理與儲存
擷取的資料可能存在格式不一致或缺漏的問題,使用 pandas
進行資料清理,並儲存為 CSV 檔案,方便後續分析或匯入資料庫。
import pandas as pddf = pd.DataFrame(sneakers_data)
df_cleaned = df.dropna()
df_cleaned.to_csv("sneakers_data.csv", index=False)
print("資料已儲存至 sneakers_data.csv")
4. 深入探討與技術優化
實務上常會遇到更複雜的情況與需要優化的部分,以下探討幾種常見問題及其解法。
4.1 多頁資料擷取
若球鞋資料分布於多個分頁中,可透過組合頁碼參數構造 URL,使用迴圈依序擷取所有頁面。
import timeall_data = []
base_url = "https://juicestore.tw/sneakers?page="
for page in range(1, 6): # 假設擷取前5頁
url = base_url + str(page)
response = requests.get(url, headers=headers)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
items = soup.find_all("div", class_="sneaker-item")
for item in items:
title = item.find("h2").get_text(strip=True) if item.find("h2") else "無名稱"
price = item.find("span", class_="price").get_text(strip=True) if item.find("span", class_="price") else "無價格"
all_data.append({
"title": title,
"price": price
})
time.sleep(2) # 延遲2秒避免過快請求
df_all = pd.DataFrame(all_data).dropna()
df_all.to_csv("sneakers_all_pages.csv", index=False)
print("所有頁面資料已儲存至 sneakers_all_pages.csv")
4.2 異常處理與反爬策略
擷取過程中可能會遇到請求失敗、網路逾時或反爬機制(如驗證碼、IP 封鎖)等問題,建議:
設定異常處理:使用 try-except 捕捉例外並重試。
使用代理:配置代理池以分散請求來源。
隨機延遲與 User-Agent:模擬真實使用者行為,降低被封鎖風險。
4.3 非同步擷取與大規模資料
若資料量龐大,建議使用非同步爬蟲或專業框架如 aiohttp
或 Scrapy
,可顯著提升效率並更好地管理請求與回應。
4.4 動態資料載入與 Selenium
若網站使用 JavaScript 動態載入資料,傳統 requests 取得的 HTML 可能不包含目標資料,需透過 Selenium 模擬瀏覽器操作,或觀察頁面 API 請求直接擷取資料。
5. 資料分析與視覺化(延伸)
擷取的球鞋資料不僅可作為展示用途,也可用於市場分析,例如:
價格趨勢分析:使用 pandas 統計不同品牌或型號的價格變化。
熱門款式統計:統計不同型號、顏色與風格的數量,觀察市場偏好。
視覺化展示:使用
matplotlib
或seaborn
畫出長條圖、折線圖或圓餅圖,讓資料更直觀。
以下是一個價格分布直方圖的示例:
import matplotlib.pyplot as pltdf_all['price'] = df_all['price'].str.replace(r'\D', '', regex=True).astype(float)
plt.hist(df_all['price'], bins=20)
plt.xlabel("價格")
plt.ylabel("頻次")
plt.title("球鞋價格分布")
plt.show()
6. 總結與展望
本文詳細介紹了如何使用 Python 擷取 juicestore.tw 網站上球鞋相關資料的完整流程,從環境準備、資料擷取、解析、清理到儲存均做出說明。實務開發中應注意符合法律規定與網站政策,設計合適的擷取策略,避免對伺服器造成影響。
未來可進一步擴展專案功能,例如:
建立更完整的資料清理與處理流程
對資料進行深度分析與機器學習預測
建立即時監控系統,追蹤市場變化
透過不斷優化與實作經驗累積,你將能打造出一個高效、穩定且功能齊全的資料擷取與分析系統。
7. 附錄
完整程式碼範例
import requestsfrom bs4 import BeautifulSoup
import pandas as pd
import time
import matplotlib.pyplot as plt
base_url = "https://juicestore.tw/sneakers?page="
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
}
all_data = []
for page in range(1, 6):
url = base_url + str(page)
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
items = soup.find_all("div", class_="sneaker-item")
for item in items:
title = item.find("h2").get_text(strip=True) if item.find("h2") else "無名稱"
price = item.find("span", class_="price").get_text(strip=True) if item.find("span", class_="price") else "無價格"
all_data.append({
"title": title,
"price": price
})
except Exception as e:
print(f"擷取第 {page} 頁資料時出錯:", e)
time.sleep(2)
df = pd.DataFrame(all_data).dropna()
df.to_csv("sneakers_all_pages.csv", index=False)
print("資料已儲存至 sneakers_all_pages.csv")
df['price'] = df['price'].str.replace(r'\D', '', regex=True)
df = df[df['price'] != '']
df['price'] = df['price'].astype(float)
plt.hist(df['price'], bins=20)
plt.xlabel("價格")
plt.ylabel("頻次")
plt.title("球鞋價格分布")
plt.show()
Articles related to APIs :
A Comprehensive Guide to Sneaker API: Your Ultimate Tool for Sneaker Data Access
Free Sneaker API Application: A Detailed Guide and Usage Introduction
Advanced Data Parsing and API Optimization: Building a More Efficient Sneaker API Application
How to Enhance Your Sneaker Data Collection with Sneaker API