給定百度百科詞條 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] + "...")
decode('gbk') 再統一轉 UTF-8re.S:讓 . 匹配換行,跨行抓取內容re.sub(r'<[^>]+>', '', text) 簡單有效BeautifulSoup / lxml 替代正則,結構更穩健time.sleep() 禮貌爬蟲間隔robots.txt 與網站服務條款爬蟲僅供學習研究,大規模抓取請申請官方 API 或取得授權,避免違反《計算機信息網絡國際聯網管理暫行規定》等法規。