Đọc mã HTML từ website với C#
Bài viết này mình giới thiệu với mấy bạn cách đọc lấy mã HTML trong một website như thế nào? Chỉ cần vài dòng code là bạn có thể thực hiên được. Trước hết bạn thiết kế form như sau: - Sau khi các bạn thiết kế form như hình trên bạn viết cho mình 3 thủ ...
Bài viết này mình giới thiệu với mấy bạn cách đọc lấy mã HTML trong một website như thế nào? Chỉ cần vài dòng code là bạn có thể thực hiên được. Trước hết bạn thiết kế form như sau:

- Sau khi các bạn thiết kế form như hình trên bạn viết cho mình 3 thủ tục sau:
+ Thủ tục đọc lấy mã HTML:
private void processHTML(String htmlContent)
{
// Obtain the document interface
IHTMLDocument2 htmlDocument = (IHTMLDocument2)new mshtml.HTMLDocument();
// Construct the document
htmlDocument.write(htmlContent);
listBox1.Items.Clear();
// Extract all image elements
IHTMLElementCollection imgElements = htmlDocument.images;
// Iterate through each image element
foreach (IHTMLImgElement img in imgElements)
{
listBox1.Items.Add(img.src);
}
}
private void LoadHTML()
{
// WebClient object
WebClient client = new WebClient();
// Retrieve resource as a stream
Stream data = client.OpenRead(new Uri(textBox2.Text));
// Retrive the text
StreamReader reader = new StreamReader(data);
string htmlContent = reader.ReadToEnd();
textBox1.Text = htmlContent;
// Call function to process HTML Content
processHTML(htmlContent);
// Cleanup
data.Close();
reader.Close();
}
+ Kế tiếp bạn viết thủ lục lấy hình ảnh trên trang website:
private void previewGallery()
{
// Iterate through all the items in the listbox
for (int i = 0; i < listBox1.Items.Count - 1; i++)
{
// Create PictureBox dynamically
// and set its properties
PictureBox pic = new PictureBox();
pic.Width = 100;
pic.Height = 100;
pic.SizeMode = PictureBoxSizeMode.StretchImage;
// Assign location of picture
// from the listbox
pic.ImageLocation = listBox1.Items[i].ToString();
// Add PictureBox to a panel
flowLayoutPanel1.Controls.Add(pic);
}
}
- Bây giờ sử dụng chúng như thế nào đây, tại nút "Thực hiện" bản chỉ gọi đến hàm LoadHTML(), còn tại nút load hình ảnh bạn gọi đến hàm previewGallery().
Hy vọng với thủ thuật nhỏ giúp ích cho các bạn.
Download Project