如何抓取 youtube 视频上的评论数量?

时间:2020-12-20 15:47:42

标签: python selenium selenium-webdriver

我正在尝试使用 selenium 和 BeautifulSoup 对 youtube 的某个视频制作评论语料库。 (由于限制,我没有尝试使用 Youtube Data api。)

我几乎做到了,但我本可以只用评论和 ID 就得到结果......

我检查了包含喜欢计数信息的空间,然后我将它输入到我的代码中,无论如何它运行良好,但它没有检索结果,它什么也没给我...... idk 为什么。 .....

import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import pandas as pd 
import re
from collections import Counter
from konlpy.tag import Twitter

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome(executable_path='C:\chrome\chromedriver_win32\chromedriver.exe', options=options)
url = 'https://www.youtube.com/watch?v=D4pxIxGdR_M&t=2s'
driver.get(url)
driver.implicitly_wait(10)

SCROLL_PAUSE_TIME = 3

# Get scroll height
last_height = driver.execute_script("return document.documentElement.scrollHeight")

while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight);")

    # Wait to load page
    time.sleep(SCROLL_PAUSE_TIME)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.documentElement.scrollHeight")
    if new_height == last_height:
        break
    last_height = new_height

html_source = driver.page_source

driver.close()

soup = BeautifulSoup(html_source, 'lxml')

ids = soup.select('div#header-author > a > span')

comments = soup.select('div#content > yt-formatted-string#content-text')

likes = soup.select('ytd-comment-action-buttons-renderer#action-buttos > div#tollbar > span#vote-count-middle')

print('ID :', len(ids), 'Comments : ', len(comments), 'Likes : ' ,len(likes))

和0只是打印出来...我已经搜索了一些处理它的方法,但大多数答案只是为了让我使用api。

1 个答案:

答案 0 :(得分:0)

我实际上不会使用 BeautifulSoup 进行提取,只需使用内置的 selenium 工具,即:

ids = driver.find_elements_by_xpath('//*[@id="author-text"]/span')
comments = driver.find_elements_by_xpath('//*[@id="content-text"]')
likes = driver.find_elements_by_xpath('//*[@id="vote-count-middle"]')

这样你仍然可以使用 len() 因为它们是可迭代的。您还可以遍历变量 likes 并获取 .text 值以将它们相加:

total_likes = 0
for like in likes:
    total_likes += int(like.text)

为了让这个更像 Pythonic,你最好使用适当的列表理解。