分享: 利用Readability解決網頁正文提取問題


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

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

雖然可以用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();
    }
}

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM