Today Yewon Learned

[C#] HtmlAgilityPack을 이용한 웹 크롤링 본문

C#

[C#] HtmlAgilityPack을 이용한 웹 크롤링

데브워니 2022. 11. 8. 10:02

1. 도구(T) - NuGet패키지 관리자 - 솔루션용 NuGet패키지 관리탭에서 HtmlAgilityPack을 다운로드한다.

 

 

2. 아래와 같이 디자이너 폼을 구성한다.

· Form1.Designer.cs

 

3. 아래 코드를 작성한다.

· Form1.cs

using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WEBCrawling
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using(WebClient client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;
                string htmlSource = client.DownloadString("http://" + txtURL.Text);
                txtResult.Text = htmlSource;
                Console.WriteLine(htmlSource);
                Console.ReadLine();
                HTMLParser parser = new HTMLParser();
                parser.ParseHTML(htmlSource, this.txtHyperLink, this.txtTitle, this.txtImg);

            }
        }
    }

    public class HTMLParser
    {
        public void ParseHTML(string htmlSource, TextBox hyperLink, TextBox title, TextBox img)
        {
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(htmlSource);
            
            title.Text = doc.DocumentNode.SelectSingleNode("//head/title").InnerText;

                foreach (HtmlNode bodyNode in doc.DocumentNode.SelectNodes("//body"))
                {
                    foreach(HtmlNode aNode in bodyNode.SelectNodes("//a"))
                    {
                        string hrefValue = aNode.Attributes["href"]?.Value;
                        hyperLink.Text += hrefValue + "\n";
                        Console.WriteLine("a href:" + hrefValue);
                    }

                    foreach (HtmlNode imgNode in bodyNode.SelectNodes("//img"))
                    {
                        string src = imgNode.Attributes["src"]?.Value;
                        img.Text += src + "\n";
                        Console.WriteLine("src:" + src);
                    }
                }
        }
    }
}

 

 

4. 결과

 

[참조] (동영상)C# HtmlAgilityPack을 이용한 웹크롤러(Web-Crawler) 웹페이지, HTML 파싱하기 (ojc.asia)

 

(동영상)C# HtmlAgilityPack을 이용한 웹크롤러(Web-Crawler) 웹페이지, HTML 파싱하기

(동영상)C# HtmlAgilityPack을 이용한 웹크롤러(Web-Crawler) 웹페이지, HTML 파싱하기HtmlAgilityPack을 이용한 웹크롤러웹페이지, HTML 파싱하기HtmlAgility, WebClient를 이용한 웹크롤러 만들기(Web-Crawler)HtmlAgilityPa

ojc.asia

 

Comments