文章出處

最近自己找了一個開源的博客網站,放到阿里云上,方便自己發布博客。

我一般把文章發布到博客園和QQ空間,家了這個網站后又要多發布一次,為了省事就做了一個從博客園讀取文章的功能;

 

輸入鏈接URL地址點擊提交;

 

 

GetHub安裝HtmlAgilityPack

后臺C#代碼

 

 

public ActionResult LinkBlog(string urlStr)
        {
            Response response = new Response() { Code =1 };
            if (string.IsNullOrWhiteSpace(urlStr))
            {
                response.Code = 0;
                response.Message = "鏈接URL必填";
                return Json(response);
            }

            WebClient c = new WebClient();
            c.Encoding = Encoding.GetEncoding("UTF-8");
            string html = c.DownloadString(urlStr);

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);
            HtmlNode nodeinfo = doc.GetElementbyId("post_detail");

            //post_detail
            //
            HtmlNode nodetitle = doc.GetElementbyId("cb_post_title_url");

            //cnblogs_post_body

            HtmlNode nodecontent = doc.GetElementbyId("cnblogs_post_body");

            string htmlstr = nodeinfo.OuterHtml;

            Blog blog = new Blog();
            blog.Publish = true;
            blog.Title =string.Format("鏈接文章:{0}", nodetitle.InnerText);
            blog.Volume = 0;
            blog.Content = htmlstr;
            blog.CreateTime = DateTime.Now;
            string htmlsumm = nodecontent.InnerText.Replace(" ", "");
            int sublen = htmlsumm.Length;
            if (sublen > 80)
            {
                sublen = 80;
            }
            blog.Summary = htmlsumm.Substring(0, sublen);

            blog.Category=  categoryManager.FindRoot()[0];
            response = blogManager.AddBlog(blog);

            return Json(response);
        }

 

應用的技術

 

WebClient c = new WebClient();

            c.Encoding = Encoding.GetEncoding("UTF-8");

            string html = c.DownloadString(urlStr);

通過WebClient讀取網頁,注意這里的編碼問題,有的網頁用的是UTF-8有的是GB2312

自己嘗試一下就知道了,編碼設置錯誤會出現漢子亂碼。

 

HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(html);

            HtmlNode nodeinfo = doc.GetElementbyId("post_detail");

 

讀取HTML字符串中指定id的標簽的內容;

參考博客:http://www.cnblogs.com/ITmuse/archive/2010/05/29/1747199.html

 

最終我不用再重復添加博客了,不過還多虧博客園沒有做圖片防盜鏈,否則圖片還要單獨處理。

 


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜

    大師兄 發表在 痞客邦 留言(0) 人氣()