NeuroWhAI의 잡블로그

[C#] Selenium을 이용해 YouTube 추천 동영상 파싱하기 본문

개발 및 공부/라이브러리&프레임워크

[C#] Selenium을 이용해 YouTube 추천 동영상 파싱하기

NeuroWhAI 2018. 5. 7. 12:52


이번 휴가에 해결하겠지만 지금은 사지방에서 구글 로그인이 안됩니다.
그래서 평소에 자주 유튜브 추천 영상을 보던걸 못하게 되어서 반강제로 건전한(?) 나날을 보내고 있었지만
이렇게는 못살겠다(?) 싶어서 제 클라우드 서버를 활용하기로 했습니다.

만들고 바로 다음날 구글 로그인이 되기 시작했습니다 ㅂㄷㅂㄷ....
ㅠㅠ 조금만 더 빨리 만들껄...
그래도 자료로서 글은 올려봅니다.

코드 조각은 이러합니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
using (IWebDriver driver = new ChromeDriver("."))
{
    var driverWait = new WebDriverWait(driver, TimeSpan.FromSeconds(10.0));
 
 
    driver.Url = "https://accounts.google.com/signin/v2";
 
    driverWait.Until(ExpectedConditions.ElementExists(By.Name("identifier")));
    var emailBox = driver.FindElement(By.Name("identifier"));
    emailBox.SendKeys(GoogleId);
    emailBox.SendKeys(Keys.Enter);
 
    driverWait.Until(ExpectedConditions.ElementExists(By.Name("password")));
    var pwdBox = driver.FindElement(By.Name("password"));
    pwdBox.SendKeys(GooglePwd);
    pwdBox.SendKeys(Keys.Enter);
 
 
    driverWait.Until(ExpectedConditions.ElementExists(By.Id("i3")));
 
 
    driver.Url = "https://www.youtube.com";
 
    driverWait.Until(ExpectedConditions.ElementExists(By.Id("video-title")));
 
    await Task.Delay(3000);
 
    var videoList = driver.FindElements(By.Id("video-title"));
 
    foreach (var video in videoList)
    {
        string title = video.Text;
        if (string.IsNullOrWhiteSpace(title))
        {
            title = "UNTITLED";
        }
 
        string url = video.GetAttribute("href");
        if (string.IsNullOrWhiteSpace(url))
        {
            url = "???";
        }
 
        Console.WriteLine("{0} : {1}", title, url);
    }
 
 
    driver.Quit();
}
cs

복잡한 처리는 라이브러리가 다 하고 저는 그냥 어떻게 제어할껀지만 코딩해주면 됬기에 코드가 짧습니다.
꼼수스러운 게 좀 있어서 시간이 지나면 또 수정해야 할 듯요.

아래는 작동하는 모습.
(원랜 영상으로 캡쳐하고 싶었는데 서버에 그런 프로그램이 잘 안돌아가서.. ㅠ)








Comments