Tuesday, March 8, 2016

Get HTML code from a website C# | Nhận mã HTML từ một trang web C #

Get HTML code from a website C# | Nhận mã HTML từ một trang web C #


- Trong 1 số trường hợp làm phần mềm thì chắc hẳn ai cũng phải va chạm tới chương trình nào đấy cần lấy 1 thông tin nào đấy từ internet về.
- Vậy cách để giải quyết vấn đề này là mình phải lấy html website đó về và tiến hành lọc thông tin cần thiết. Vậy phương pháp nào tối ưu để lấy html về trong ngôn ngữ lập trình C#. Sau đây Cường xin giới thiệu với các bạn các cách như sau:
Cách 1: Sử dụng HttpWebRequest
public static String code(string Url)
{

        HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
        myRequest.Method = "GET";
        WebResponse myResponse = myRequest.GetResponse();
        StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
        string result = sr.ReadToEnd();
        sr.Close();
        myResponse.Close();

        return result;
 }
Cách 2:  Tốt nhất, bạn có thể sử dụng lớp WebClient để đơn giản hóa công việc của bạn

using System.Net;

using (WebClient client = new WebClient())
{
     client.Encoding = Encoding.UTF8;
     client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0");
     client.Headers.Add(HttpRequestHeader.Cookie, webBrowser1.Document.Cookie);
     richTextBox1.Text = client.DownloadString("https://www.facebook.com");
}

Cách 3: Cách được đánh giá là cơ bản trên stackoverflow

using System.Net;
using System.Net.Http;  // in LINQPad, also add a reference to System.Net.Http.dll

WebRequest req = HttpWebRequest.Create("http://google.com");
req.Method = "GET";

string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
    source = reader.ReadToEnd();
}

Console.WriteLine(source);
Cách 4: Ngắn gọn không cần mất sức

var html = new System.Net.WebClient().DownloadString(siteUrl)
Cách 5: Dùng Chilkat asembly

Chilkat.Http http = new Chilkat.Http();

bool success;

//  Any string unlocks the component for the 1st 30-days.
success = http.UnlockComponent("Anything for 30-day trial");
if (success != true) {
    Console.WriteLine(http.LastErrorText);
    return;
}

//  Send the HTTP GET and return the content in a string.
string html;
html = http.QuickGetStr("http://www.wikipedia.org/");

Console.WriteLine(html);

- Trên đây là những cách mà mình đã sưu tầm lại được, nếu có những cách mới thì các bạn comment ở dưới nhé. Nếu hay thì share cho bạn bè cùng biết để cùng học tập nào. Hẹn gặp lại các bạn vào tut sắp tới.

Bài Viết Liên Quan