萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 爬取百度百科詞條標題與摘要

目標

給定百度百科詞條 URL,擷取 <h1 class="title"> 標題與 <div class="card-summary-content"> 摘要內容。

完整程式碼


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib.request
import re
import sys

def fetch_html(url, timeout=10):
    req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return resp.read()

def clean_html(text):
    # 移除 HTML 標籤、多餘空白
    text = re.sub(r'<[^>]+>', '', text)
    text = re.sub(r'\s+', ' ', text).strip()
    return text

if __name__ == '__main__':
    url = 'https://baike.baidu.com/item/Python/407313'
    html = fetch_html(url)
    # 百度百科頁面編碼為 GBK/GB2312
    html = html.decode('gbk', 'replace').encode('utf-8').decode('utf-8')

    title_pat = r'

]*>(.*?)

' summary_pat = r'
]*>(.*?)
' title = re.search(title_pat, html, re.S) summary = re.search(summary_pat, html, re.S) if title: print("標題:", clean_html(title.group(1))) if summary: print("摘要:", clean_html(summary.group(1))[:200] + "...")

關鍵點

  1. 編碼處理:百度頁面為 GBK,需 decode('gbk') 再統一轉 UTF-8
  2. 正則旗標 re.S:讓 . 匹配換行,跨行抓取內容
  3. User-Agent:模擬瀏覽器避免 403
  4. 去標籤:re.sub(r'<[^>]+>', '', text) 簡單有效

擴充建議

  • 使用 BeautifulSoup / lxml 替代正則,結構更穩健
  • 加入 time.sleep() 禮貌爬蟲間隔
  • 處理重導向、驗證碼、登入狀態
  • 遵守 robots.txt 與網站服務條款

法律與道德提醒

爬蟲僅供學習研究,大規模抓取請申請官方 API 或取得授權,避免違反《計算機信息網絡國際聯網管理暫行規定》等法規。

copyright © 萬盛學電腦網 all rights reserved