HTTP 網路連線請求
`urllib.request` 是 Python 內建的網址存取模組,可以透過 HTTP 或 HTTPS 取得網路上的資料。基本流程如下:
1. 使用 `urlopen()` 開啟網址。
2. 使用 `read()` 讀取回應內容。
3. 網路資料通常是 `bytes`,先用 `decode("utf-8")` 轉成字串。
4. 使用 `json.loads()` 將 JSON 字串轉成 Python 物件。
5. 取出每個產品的價格,計算平均值。
```python
from urllib.request import urlopen
import json
url = "https://cwpeng.github.io/live-records-samples/data/products.json"
# 開啟網址並取得資料
with urlopen(url) as response:
data = response.read().decode("utf-8")
# 將 JSON 格式的字串轉成 Python 資料
products = json.loads(data)
# 取出所有產品的價格
prices = [product["price"] for product in products]
# 計算平均價格
average_price = sum(prices) / len(prices)
print("產品數量:", len(products))
print("平均價格:", average_price)
print(f"平均價格:{average_price:.2f}")
```
### 程式說明
#### 1. 匯入模組
```python
from urllib.request import urlopen
import json
```
- `urlopen()`:開啟網址並取得回應。
- `json`:處理 JSON 格式資料。
#### 2. 取得網址內容
```python
with urlopen(url) as response:
data = response.read().decode("utf-8")
```
`urlopen()` 回傳的是一個回應物件:
- `response.read()` 讀出內容,型別通常是 `bytes`。
- `decode("utf-8")` 將位元組資料轉成文字。
- `with` 區塊結束後,會自動關閉網路連線。
#### 3. 解析 JSON
```python
products = json.loads(data)
```
如果 JSON 內容是一個產品陣列,例如:
```json
[
{"name": "產品 A", "price": 100},
{"name": "產品 B", "price": 200}
]
```
解析後會變成 Python 的 `list`,其中每個產品是 `dict`。
#### 4. 計算平均價格
```python
prices = [product["price"] for product in products]
average_price = sum(prices) / len(prices)
```
- 使用串列生成式取得所有 `price`。
- `sum(prices)` 計算價格總和。
- `len(prices)` 計算產品數量。
- 總和除以數量就是平均價格。
也可以使用 `statistics.mean()` 計算平均值:
```python
from urllib.request import urlopen
from statistics import mean
import json
url = "https://cwpeng.github.io/live-records-samples/data/products.json"
with urlopen(url) as response:
products = json.loads(response.read().decode("utf-8"))
average_price = mean(product["price"] for product in products)
print(f"平均價格:{average_price:.2f}")
```
若要處理網址連線失敗或資料格式錯誤,可以加入例外處理:
```python
from urllib.request import urlopen
from urllib.error import URLError, HTTPError
import json
url = "https://cwpeng.github.io/live-records-samples/data/products.json"
try:
with urlopen(url, timeout=10) as response:
products = json.loads(response.read().decode("utf-8"))
prices = [product["price"] for product in products]
average_price = sum(prices) / len(prices)
print(f"平均價格:{average_price:.2f}")
except HTTPError as error:
print("HTTP 錯誤:", error.code)
except URLError as error:
print("網址連線錯誤:", error.reason)
except (KeyError, ValueError, ZeroDivisionError) as error:
print("資料格式或內容錯誤:", error)
```
相關學習地圖、教學課程
Python 資料工程
Python 後端工程、資料庫