본문 바로가기

PYTHON/자동화

유튜브영상링크 스크롤 끝까지 크롤링

728x90

답글과 자세히보기는 x
뭔가 로딩이 느려서 안되는 경우도 많음 ㅠㅠ

한 페이지에 20개씩 보이는 거 같길래

(댓글 수/20)번 내렸는데 답글 수까지 포함된 수라는 걸 생각을 못해서 답글이 많이 달린 영상이라면 

헛으로 키를 누르는 경우가 많을 수 있고,

간단한 문제인데 내릴때마다 다시 맨 위로 올라가서 답답했다.

근데 END키를 쓰면 맨 밑으로 내려가긴하는데 로딩이 안되서 계속 현재까지 불러온 페이지 크기까지만 스크롤해서 다음 화면을 불러왔다.

 

맨날 진도는 안나가고 막히는 거 같다 ㅠㅠ 원래는 댓글수집해서 텍스트마이닝 해보고싶었는데 생각보다 너무 복잡하다

import time
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
from bs4 import BeautifulSoup
import urllib
import re
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome('C:\chromedriver.exe')
driver.get("https://www.youtube.com/user/Sunbaaking/videos")

driver.maximize_window()

source = driver.page_source
soup = BeautifulSoup(source,'html.parser')

mainlink = "https://www.youtube.com/"
titles=[]
links=[]
SCROLL_PAUSE_TIME=5



def scroll_down_end():
    driver.execute_script("window.scrollTo(0, 400);")
    time.sleep(SCROLL_PAUSE_TIME)

    source = driver.page_source
    soup = BeautifulSoup(source,'html.parser')

    last_height = driver.execute_script("document.documentElement.scrollHeight")


    comment_count = soup.find("yt-formatted-string", class_ ="count-text style-scope ytd-comments-header-renderer")    

    repeat=(comment_count.get_text())
    print(repeat) # 댓글 xxx개


    num = re.findall("\d+",repeat)
    print(num)

    for i in num:
        count = float(num[0])

    print(count)
    count_int=int(round(count)/20)

    # while True:
    for i in range(count_int):
        # 끝까지 스크롤 내리기

        ActionChains(driver).key_down(Keys.END).perform()
        time.sleep(SCROLL_PAUSE_TIME)
        ActionChains(driver).key_up(Keys.END).perform()
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")



        # 쉬기
        time.sleep(SCROLL_PAUSE_TIME)

#         # 불러올 스크롤이 없으면 그만하기
#         new_height = driver.execute_script("document.documentElement.scrollHeight")
#         if new_height == last_height:
#             break
#         last_height = new_height


# links=soup.findAll('a',id='video-title') 같은 코드
titles=soup.select("a[id=video-title]")
for title in titles:
    print(title.text)
    print(mainlink+title.get('href'))


title0=titles[0]
driver.get(mainlink+title0.get('href'))
#body=driver.find_element_by_tag_name('body')
#body.text


scroll_down_end()
print("스크롤 후")


ActionChains(driver).key_down(Keys.END).key_up(Keys.END).perform()
source = driver.page_source
soup = BeautifulSoup(source,'html.parser')

comments=soup.select("yt-formatted-string[id=content-text]")
for comment in comments:
    print(comment.text)

# comment_count = soup.find("yt-formatted-string", class_ ="count-text style-scope ytd-comments-header-renderer")    

# repeat=(comment_count.get_text())
# print(repeat) # 댓글 xxx개


# num = re.findall("\d+",repeat)
# print(num)


print(len(comments))