利用Readability解決網頁本文提取問題

來源:互聯網
上載者:User

做資料抓取和分析的各位親們, 有沒有遇到下面的難題呢?

- 如何從各式各樣的網頁中提取本文!?

雖然可以用SS為各種網站寫指令碼做解析, 但是互連網各類網站何止千萬種, 縱 使累死我們也是做不完的. 這裡我給大家熱情推薦使用Readability來徹底解決這 個難題 (呵呵, 不是做廣告, 真心熱愛這個好東東)

Raedability網站(www.readability.com)最引以為傲的就是其強大的解析引擎 , 號稱世界上最強大的文本解析神器. Safari中的"閱讀器"功能就是 用它來實現的! 他們還提供了API可以調用解析器的功能, 而我做了一個c#的代理 類來方便大家使用.

開始之前請大家自行註冊readability並申請appkey, 免費的.

代理類代碼:

public static class ReadabilityProxy{    public static Article Parse(string url, string token) //token就是各位的appkey    {        WebClient wc = new WebClient();        wc.Encoding = Encoding.UTF8;        var encUrl = HttpUtility.UrlEncode(url);        Uri u = new Uri(string.Format("https://readability.com/api/content/v1/parser?url={0}&token={1}", encUrl, token));        var json = wc.DownloadString(u);        JavaScriptSerializer se = new JavaScriptSerializer();        return se.Deserialize(json, typeof(Article)) as Article;    }}   public class Article{    public string Domain;    public string Next_Page_Id;    public string Url;    public string Content;    public string Short_Url;    public string Excerpt;    public string Direction;    public int Word_Count;    public int Total_Pages;    public string Date_Published;    public string Dek;    public string Lead_Image_Url;    public string Title;    public int Rendered_Pages;       public virtual void Decode()    {        this.Excerpt = HttpUtility.HtmlDecode(this.Excerpt);        this.Content = HttpUtility.HtmlDecode(this.Content);    }}

由於readability返回的Content, Excerpt都是編碼過的, 因此我提供了 Article.Decode方法來解碼.

在ConsoleApp中測試效果:

class Program{    static void Main(string[] args)    {        var article = ReadabilityProxy.Parse("http://www.mot.gov.cn/st2010/shanghai/sh_zhaobiaoxx/201203/t20120330_1219097.html", "***此處省略n個字***");         article.Decode();        Console.WriteLine(article.Title);        Console.WriteLine(article.Excerpt);        Console.WriteLine(article.Content);        Console.ReadLine();    }}

怎麼樣? 效果不錯吧, 趕快試試吧!

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.