【问题标题】:How to scrape youtube comments using BeautifulSoup如何使用 BeautifulSoup 抓取 youtube 评论
【发布时间】:2018-04-18 19:49:45
【问题描述】:

我是新手。我想知道如何使用 BeautifulSoup 抓取 YouTube cmets。我被这里击中了。谁能帮我写代码。

这是我写的:

import requests    
from bs4 import BeautifulSoup

r = requests.get("https://www.youtube.com/watch?v=kffacxfA7G4"    
req =r.conten    
soup = BeautifulSoup(req,'html.parser')    
print(soup.prettify())    
all = soup.find_all('div',{'id' : 'contents'})

我被困在这里没有得到任何输出,检查它显示 cmets 的 wb 页面有 id = contents

【问题讨论】:

  • 这是学习BeautifulSoup,还是需要和Youtube互动?你可以使用 Youtube 的 API - developers.google.com/youtube/v3/docs/comments/list
  • 嗨,@Robert Seaman。我正在学习 BeautifulSoup 并试图让 youtube cmets 练习。我觉得很难做到。你能帮我解决这个问题吗?
  • 有更容易学习的页面BeautifulSoup。像 youtube 这样更高级的网站通常通过 javascript 加载页面,因此如果您只使用 requests.get,您将不会看到太多数据。也许尝试使用w3schools.comexample.com
  • 另外,请格式化你的代码,这个sn-p不能通过复制粘贴运行,因为它不完整

标签: python python-3.x web-scraping beautifulsoup


【解决方案1】:

该网站的评论是动态生成的。您无法通过使用 requestsBeautifulSoup 库的主链接获取它们。要获取跟踪上述链接的内容,您需要使用任何浏览器模拟器,例如selenium。作为初学者,您可以尝试如下。以下脚本将为您获取展开的 cmets。顺便说一句,该网站还启用了延迟加载方法,因此您需要抽动for loop 以获取更多内容。

import time
from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

with Chrome() as driver:
    wait = WebDriverWait(driver,10)
    driver.get("https://www.youtube.com/watch?v=kffacxfA7G4")

    for item in range(3): #by increasing the highest range you can get more content
        wait.until(EC.visibility_of_element_located((By.TAG_NAME, "body"))).send_keys(Keys.END)
        time.sleep(3)

    for comment in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#comment #content-text"))):
        print(comment.text)

部分输出:

15 April 2018 ?¿?
April 2018??
8 years people ?
Nice songs Justin Bieber https://youtu.be/OvfAc7JGoc4
2018 hit like...♥️♥️♥️♥️???
8 years complete ?
Can likes beat dislikes??
View 1, 8 billion great song

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 2016-11-14
    • 1970-01-01
    • 2018-04-12
    • 2014-10-03
    • 2018-08-29
    • 2019-09-06
    • 2022-11-03
    • 2022-08-18
    相关资源
    最近更新 更多