萬盛學電腦網

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

Python 爬取博客生成 RSS 訂閱源

許多部落格平台提供的 RSS 僅含摘要,若需全文訂閱,可自行撰寫爬蟲抓取文章內容並生成標準 RSS 2.0 XML。本文展示使用 BeautifulSoup 解析 HTML、PyRSS2Gen 產生 RSS 的完整腳本。

核心流程

  1. 請求部落格列表頁,解析最新文章連結。
  2. 逐一進入文章頁,提取標題、發布時間、正文內容。
  3. 建立 RSSItem 加入 RSS2 物件。
  4. 輸出 XML 檔案,部署至 Web 伺服器供 RSS 閱讀器訂閱。

關鍵程式碼片段

import urllib.request
from bs4 import BeautifulSoup
import PyRSS2Gen
import datetime, re, os, sys

class RssSpider:
    def __init__(self):
        self.rss = PyRSS2Gen.RSS2(
            title='OSChina Blog',
            link='https://my.oschina.net',
            description=str(datetime.date.today()),
            pubDate=datetime.datetime.now(),
            items=[]
        )
        self.xml_path = '/var/www/myrss/oschina.xml'
        self.base_url = 'https://www.oschina.net/blog'

    def fetch(self, url):
        headers = {'User-Agent': 'Mozilla/5.0 ...'}
        req = urllib.request.Request(url, headers=headers)
        return urllib.request.urlopen(req).read()

    def parse_article(self, url):
        html = self.fetch(url)
        soup = BeautifulSoup(html, 'html.parser')
        title = soup.title.string
        content_div = soup.find('div', class_='BlogContent')
        pub_date = self.extract_date(soup)
        return PyRSS2Gen.RSSItem(
            title=title, link=url,
            description=str(content_div),
            pubDate=pub_date
        )

    def extract_date(self, soup):
        # 從頁面抓取日期,失敗則用今天
        stat = soup.find('div', class_='BlogStat')
        # ... 正則解析日期 ...
        return datetime.date.today()

    def crawl(self):
        html = self.fetch(self.base_url)
        soup = BeautifulSoup(html, 'html.parser')
        for li in soup.find('div', id='RecentBlogs').find_all('li'):
            link = li.find('a')['href']
            self.rss.items.append(self.parse_article(link))

    def save(self):
        with open(self.xml_path, 'w', encoding='utf-8') as f:
            f.write(self.rss.to_xml(encoding='utf-8'))

if __name__ == '__main__':
    spider = RssSpider()
    spider.crawl()
    spider.save()

部署建議

  • 將腳本放入 cron 定時執行 (如每小時)。
  • 輸出 XML 放在 Nginx/Apache 靜態目錄,設定正確 Content-Type: application/rss+xml。
  • 加入錯誤重試、日誌記錄、User-Agent 輪換以防反爬。
  • 遵守 robots.txt 與網站服務條款,適當設定抓取間隔。

擴充方向

  • 支援多部落格來源,輸出合併或分類 RSS。
  • 整合 feedparser 驗證生成的 XML 格式正確性。
  • 使用 apscheduler 取代 cron 實現進程內排程。

自製 RSS 橋接器能讓你掌握資訊獲取方式,免受平台限制。

copyright © 萬盛學電腦網 all rights reserved