作者分享使用 Python 撰寫簡易爬蟲下載廖雪峰 Python 教程網頁並儲存為 HTML 的過程。程式碼約 50 行,展示 urllib 爬取、字串處理提取連結、解析標題與內文、儲存檔案等核心步驟。
<title> 當檔名。<!-- block main --> 為起點)。# coding:utf-8
import urllib
domain = 'https://www.liaoxuefeng.com'
path = r'C:\Users\cyhhao2013\Desktop\temp'
# 讀取 HTML 頭部模板
head = open(r'C:\Users\cyhhao2013\Desktop\head.html', 'r').read()
# 取得首頁內容
home = urllib.urlopen("https://www.liaoxuefeng.com/wiki/...").read()
# 移除換行空格並分割連結
geturl = home.replace("\n", "").replace(" ", "")
links = geturl.split(r'em;"><ahref="')[1:]
links.insert(0, '/wiki/...') # 強迫加入首頁
for li in links:
url = domain + li.split(r'">')[0]
print url
html = urllib.urlopen(url).read()
# 解析標題
title = html.split("")[1].split(" - 廖雪峰的官方網站 ")[0]
title = title.decode('utf-8').replace("/", " ")
# 截取正文
html = html.split(r'')[1]
html = html.split(r'您的支持是作者寫作最大的動力!
')[0]
html = html.replace(r'src="', 'src="' + domain)
# 組合完整 HTML
html = head + html + "