爬取知乎話題頁面,soup.find_all(class_="zm-item-tag") 會將父話題(如「生活情趣」)與子話題(如「養生平台」、「養胃」)混在同一個列表,無法區分層級。
觀察頁面結構,父子話題通常包裹在不同的容器中:
class="zm-topic-manage-item" 且包含 <h3> 標題。class="zm-item-tag" 形式出現。# 1. 先找到所有父話題管理項目
parent_items = soup.find_all(class_="zm-topic-manage-item")
for item in parent_items:
# 2. 判斷是否有 h3 標題,確認為父話題區塊
h3 = item.find('h3')
if h3:
parent_topic = h3.get_text(strip=True)
print(f"父話題: {parent_topic}")
# 3. 在當前父項目內部尋找子話題標籤
child_tags = item.find_all(class_="zm-item-tag")
for tag in child_tags:
child_topic = tag.get_text(strip=True)
print(f" 子話題: {child_topic}")
find_all 可限制在特定父元素內搜尋(item.find_all(...))。strip=True 去除多餘空白字元。此法可清晰建立父子話題對應關係,便於後續資料結構化儲存。