首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

部落格文章批量修改實戰 (下):F# 非同步平行下載全站文章 ID 與內容

     編輯:關於ASP.NET

接續上篇準備工作,本文實作以 F# 非同步工作流 (`async`) 結合 `WebClient` 平行下載博客園所有公開文章 ID,再透過 MetaWeblog API 批次取得/更新內容,完成 500+ 篇文章自動化修改。

階段一:非同步下載所有文章 ID

博客園「月份歸檔」頁面 URL 規則固定:`https://www.cnblogs.com/{user}/archive/{yyyy}/{mm}.html`。每頁包含「編輯」連結 `EditPosts.aspx?postid=12345`,以 Regex 擷取 ID。

type WebClient with
    member c.GetStringAsync(url) =
        async {
            let completeEvent = c.DownloadStringCompleted
            do c.DownloadStringAsync(Uri(url))
            let! args = Async.AwaitEvent(completeEvent)
            return args.Result
        }

let downloadPostIdsAsync (beginMonth: DateTime) (endMonth: DateTime) =
    let downloadMonth (m: DateTime) = async {
        let wc = new WebClient()
        let url = sprintf "https://www.cnblogs.com/JeffreyZhao/archive/%i/%i.html" m.Year m.Month
        let! html = wc.GetStringAsync(url)
        let regex = @"EditPosts\.aspx\?postid=(\d+)"
        return [ for m in Regex.Matches(html, regex) -> m.Groups.[1].Value |> Int32.Parse ]
    }
    async {
        let! lists =
            Seq.initInfinite (fun i -> beginMonth.AddMonths(i))
            |> Seq.takeWhile (fun m -> m <= endMonth)
            |> Seq.map downloadMonth
            |> Async.Parallel
        lists
        |> List.concat
        |> List.sort
        |> List.map string
        |> fun lines -> File.WriteAllLines("postIds.txt", lines)
    }

關鍵技術點

  • Async.Parallel:所有月份並發下載,大幅縮短總耗時。
  • ServicePointManager.DefaultConnectionLimit:設為 10 避免連線佇列阻塞,同時不對目標站造成過大壓力。
  • 型別提供者/腳本化:F# REPL 互動式開發,快速驗證 Regex 與 HTML 結構。

階段二:MetaWeblog API 批次讀取/更新

type Post = {
    [] PostID: int
    [] CreateTime: DateTime
    [] Title: string
    [] Content: string
    [] Categories: string[]
}

type IMetaWeblogProxy = inherit IXmlRpcProxy
    []
    abstract GetPost: postId:string * userName:string * password:string -> Post
    []
    abstract UpdatePost: postId:string * userName:string * password:string * post:Post * publish:bool -> bool

使用 `XmlRpcProxyGen.Create()` 產生 Proxy,搭配 `Async.Parallel` 批次呼叫 `GetPost`/`UpdatePost`,即可完成全站文章內容自動化修改 (如移除段首空格、統一 RSS 全文輸出)。

成果與心得

  • 500+ 篇文章、10 MB 內容,全自動化處理約 10 分鐘內完成。
  • F# 非同步工作流 + XML-RPC.NET 讓 I/O 密集型批次作業代碼極度簡潔、健壯。
  • MetaWeblog API 雖為標準,各部落格平台實作細節略異,需以目標平台實測為準。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved