Today Yewon Learned

[C#] Selenium을 이용한 실시간 검색어 크롤링하기(1) 본문

C#

[C#] Selenium을 이용한 실시간 검색어 크롤링하기(1)

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

실시간 검색어를 조회해주는 사이트를 이용하여 10위까지 검색어를 추출하여 나타내고자한다.

 

1. 시그널 실시간 검색어 사이트 분석

사이트의 HTML태그가 어떻게 구성되었는지 분석한다.

 

 

2. 도구(T) - NuGet패키지 관리자 - 솔루션용 NuGet패키지 관리탭에서 Selenium 관련 솔루션을 설치한다.

· Selenium.WebDriver

· Selenium.Support

· Selenium.WebDriver.ChormeDriver

 

 

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

· Form1.Designer.cs

 

 

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

· Form1.cs

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

//Selenium
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;

namespace Exam_Selenium
{
    public partial class Form1 : Form
    {
        protected ChromeDriverService _driverService = null;
        protected ChromeOptions _options = null;
        protected ChromeDriver _driver = null;

        public Form1()
        {
            InitializeComponent();

            try
            {
                _driverService = ChromeDriverService.CreateDefaultService();
                _driverService.HideCommandPromptWindow = true;

                _options = new ChromeOptions();
                _options.AddArgument("disable-gpu");
            }
            catch (Exception exc)
            {
                Trace.WriteLine(exc.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                _driver = new ChromeDriver(_driverService, _options);

                _driver.Navigate().GoToUrl("https://signal.bz/");

                var ranktime = _driver.FindElement(By.XPath("//*[@id='app']/div/main/div/section/div/section/section[1]/div[1]/div[1]/span")).Text;
                Console.WriteLine("ranktime:" + ranktime);

                var ranks = _driver.FindElements(By.ClassName("rank-layer"));

                foreach (var rank in ranks)
                {
                    var num = rank.FindElement(By.ClassName("rank-num")).Text;
                    var search = rank.FindElement(By.ClassName("rank-text")).Text;
                    Console.WriteLine(num + "." + search);
                }
            }

            catch (Exception exc)
            {
                Trace.WriteLine(exc.Message);
            }
        }
    }
}

 

XPath를 이용하는 방법은, 개발자모드(F12) 우클릭 후 Copy XPath를 클릭한다.

Ctrl+V 의 결과는 //*[@id="app"]/div/main/div/section/div/section/section[1]/div[1]/div[1]/span이다.

* 주의할 점은 괄호안의 큰 따옴표 " "를 작은 따옴표로 수정하여 반영해야한다.

 driver.FindElement(By.XPath("//[@id='app']/div/main/div/section/div/section/section[1]/div[1]/div[1]/span")).Text;

 

 

4. 결과

 

실행 후, 시그널 실시간 검색어사이트의 검색어를 크롤링한 결과를 확인할 수 있다.

 

[참조]

https://www.youtube.com/watch?v=zwNTiZr4jvI 

 

Comments