許多部落格平台提供的 RSS 僅含摘要,若需全文訂閱,可自行撰寫爬蟲抓取文章內容並生成標準 RSS 2.0 XML。本文展示使用 BeautifulSoup 解析 HTML、PyRSS2Gen 產生 RSS 的完整腳本。
RSSItem 加入 RSS2 物件。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 定時執行 (如每小時)。Content-Type: application/rss+xml。robots.txt 與網站服務條款,適當設定抓取間隔。feedparser 驗證生成的 XML 格式正確性。apscheduler 取代 cron 實現進程內排程。自製 RSS 橋接器能讓你掌握資訊獲取方式,免受平台限制。