Tuesday, September 29, 2015

Để lấy được nội dung website thông qua một URL bất kì. Việc đầu tiên ta phải lấy về được toàn bộ html của link đó, sau đó phân tích chuỗi html đó, dựa vào các id hoặc name của div, table, span, v.v.... mà ta sẽ lấy được nội dung cần lấy. Để làm được việc này các bạn cần có một chút kiến thức về RegularExpressions.

Do mỗi website có cấu trúc khác nhau nên cách trích lọc và phân tích html cũng khác nhau. Ở đây tôi sẽ ví dụ cho các bạn lấy nội dung tin tức từ website vnexpress.net. Cụ thể tôi sẽ lấy nội dung của link sau: http://vnexpress.net/gl/xa-hoi/2012/08/phu-nu-chet-loa-the-trong-khach-san/

Đầu tiên, các bạn add thêm 4 thư viện sau:


using System.Text.RegularExpressions;
using System.Text;
using System.Net;
using System.IO;

 
Hàm lấy html của link bất kì:
 
public string GetWebContentHTML(string strLink)
    {
        string strContent = "";
        try
        {
            WebRequest objWebRequest = WebRequest.Create(strLink);
            objWebRequest.Credentials = CredentialCache.DefaultCredentials;
            WebResponse objWebResponse = objWebRequest.GetResponse();
            Stream receiveStream = objWebResponse.GetResponseStream();
            StreamReader readStream = new StreamReader(receiveStream, System.Text.Encoding.UTF8);
            strContent = readStream.ReadToEnd();
            objWebResponse.Close();
            readStream.Close();
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
        return strContent;
    }
 
 
Bây giờ công việc tiếp theo là lấy ra từng thành phần mà bạn muốn lấy. 
 
Phân tích lấy phần tiêu đề: Các bạn viết hàm sau:
 
public string LayTieuDe(string Content)
    {
        string pattern = "

[^<]+"

;
        Regex Title = new Regex(pattern);
        Match m = Title.Match(Content);
        if (m.Success)
            return m.Value.Substring(16, m.Value.Length - 16);
        return "";
    }
 
Phân tích lời phần mô tả: Hàm được viết tương tự như sau:
 
public string LayMoTa(string Content)
    {
        string pattern = "

[^<]+"

;
        Regex Title = new Regex(pattern);
        Match m = Title.Match(Content);
        if (m.Success)
            return m.Value.Substring(15, m.Value.Length - 15);
        return "";
    }
 
 
Phân tích lấy phần nội dung. Các bạn tạo hàm sau:
 
public string LayNoiDung(string Content)
    {
        string pattern = "
[^~]+"
;
        Regex Title = new Regex(pattern);
        Match m = Title.Match(Content);
        if (m.Success)
            return m.Value.Substring(16, m.Value.Length - 16).Replace("/Files""http://vnexpress.net/Files").Replace("/gl","http://vnexpress.net/gl");
        return "";
    }
 

0 Comments:

Post a Comment