萬盛學電腦網

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

Python 撰寫簡易網頁爬蟲:以廖雪峰 Python 教程為例

作者分享使用 Python 撰寫簡易爬蟲下載廖雪峰 Python 教程網頁並儲存為 HTML 的過程。程式碼約 50 行,展示 urllib 爬取、字串處理提取連結、解析標題與內文、儲存檔案等核心步驟。

爬蟲核心流程

  1. 讀取 HTML 模板頭部。
  2. 抓取教程首頁,移除換行與空格方便解析。
  3. 分割提取所有章節連結。
  4. 逐一造訪連結,解析 <title> 當檔名。
  5. 截取正文區塊(以 <!-- block main --> 為起點)。
  6. 修正圖片相對路徑為絕對路徑。
  7. 組合完整 HTML 並儲存。

關鍵程式碼片段

# 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 + "" # 存檔 output = open(path + "%d" % links.index(li) + title + '.html', 'w') output.write(html) output.close()

現代建議: 實際專案建議使用 requests + BeautifulSoup 或 lxml 進行更健壯的解析,並加入錯誤處理、延遲與 User-Agent 設定。

copyright © 萬盛學電腦網 all rights reserved