用 colab 單純只是懶得在電腦架 python 環境,而且我也不過就是要撈資料才會用到。有部分用 AI 幫忙寫,太久沒碰程式相關
不過請它寫完自己還是順一下完整的邏輯再加一些有的沒的,所以紀錄+分析一下整個內容
安裝 使用工具
!pip install requests beautifulsoup4 pandas lxml openpyxl chardet
requests
→ 負責向網站提出請求,取得網頁內容BeautifulSoup
→ 把 HTML 解析成可以搜尋的結構pandas
→ 整理資料表openpyxl
→ 讓 pandas 可以輸出 Excelchardet
→ 避免中文亂碼
匯入套件
import requests
from bs4 import BeautifulSoup
import pandas as pd
import chardet
from datetime import datetime
import os
datetime
→ 輸出的檔案增加檔名日期避免覆蓋os
→ 避免檔案重複
目標網址&取得網頁內容&處理中文編碼
# 目標網址
url = "https://www.coolpc.com.tw/evaluate.php"
# 抓取網頁
res = requests.get(url)
# 自動偵測編碼
detected = chardet.detect(res.content)
encoding = detected["encoding"]
print(f"偵測到編碼:{encoding}")
# 正確解碼成文字
res.encoding = encoding
html_text = res.text
撈出來的資料可能不是 UTF-8,所以以防萬一先做偵測&轉譯
解析 HTML
# 用 BeautifulSoup 解析
soup = BeautifulSoup(html_text, "lxml")
# 找出所有下拉選單
selects = soup.find_all("select")
data = []
for select in selects:
parent_tr = select.find_parent('tr')
if not parent_tr:
continue
all_tds = parent_tr.find_all('td')
if len(all_tds) > 1:
category_name = all_tds[1].text.strip()
else:
continue
options = select.find_all("option")
for opt in options:
text = opt.text.strip()
if not text:
continue
if ',' in text:
try:
name, price = text.rsplit(',', 1)
price = price.strip()
except ValueError:
name = text
price = ''
else:
name = text
price = ''
data.append({
"分類": category_name,
"商品名稱": name.strip(),
"金額": price
})
找出商品位置
原價屋網站是原本是長這樣↓
全部品項都是放在選單裡面,我要撈裡面的商品品項&價錢
我很懶得用 Excel 另外處理價錢,所以事先在裡面寫了name,price = text.rsplit(',',1)
價錢基本上都在最後一個逗號後面,這段可以直接把品名和價錢幫我拆出來,保留分類、商品完整名稱和價錢。
輸出
# 建立 DataFrame
df = pd.DataFrame(data)
today_str = datetime.now().strftime('%Y%m%d')
serial_number = 1
base_filename = f"coolpc_products_{today_str}"
output_filename = f"{base_filename}_{serial_number:03d}.xlsx"
while os.path.exists(output_filename):
serial_number += 1
output_filename = f"{base_filename}_{serial_number:03d}.xlsx"
df.to_excel(output_filename, index=False, engine="openpyxl")
print(f"\n擷取完成,共 {len(df)} 筆資料。")
print(f"已輸出為:{output_filename}")
# 顯示前 10 筆資料預覽
display(df.head(10))
輸出、建檔、colab 下面可以預覽檔案資料
檔案在左上角可以直接下載出 excel