取得文字與屬性
"""第一次解析 HTML:找一個與找全部。"""
from bs4 import BeautifulSoup
# 讀取 HTML 檔案
with open("../Scraping&BeautifulSoup_datasets/迷你商店.html", "r", encoding="utf-8") as file:
html = file.read()
soup = BeautifulSoup(html, "html.parser")
# 找第一個商品
card = soup.find("article", class_="product")
# 取得商品名稱文字
name_tag = card.find("h2", class_="name")
name = name_tag.get_text(" ", strip=True)
# 取得價格
price_tag = card.find("span", class_="price")
price = price_tag.get_text(" ", strip=True)
# 取得必要屬性 data-id
product_id = card["data-id"]
# 取得連結
link = card.find("a")
href = link.get("href", "")
print("商品名稱:", name)
print("價格:", price)
print("商品編號:", product_id)
print("連結:", href)