【问题标题】:How to scrape views from Youtube pages如何从 Youtube 页面中抓取视图
【发布时间】:2020-11-25 15:54:11
【问题描述】:

我的代码大部分都很好

我目前从 youtube 页面获取所有标题 + 滚动。

我如何获得观看次数?

CSS 或 xPath 会起作用吗?

import time
from selenium import webdriver
from bs4 import BeautifulSoup
import requests
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager

options = Options()
driver = webdriver.Chrome(ChromeDriverManager().install())
url='https://www.youtube.com/user/OakDice/videos'
driver.get(url)
last_height = driver.execute_script("return document.documentElement.scrollHeight")
SCROLL_PAUSE_TIME = 2
while True:
    # Scroll down to bottom
    time.sleep(2)
    driver.execute_script("window.scrollTo(0, arguments[0]);", last_height)
    # 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
content=driver.page_source.encode('utf-8').strip()
soup=BeautifulSoup(content,'lxml')
titles = soup.findAll('a', id='video-title')
for title in titles:
    print(title.text)

【问题讨论】:

    标签: python selenium xpath css-selectors


    【解决方案1】:

    使用 YouTube API 获取有关视频的 JSON 数据可能会更可靠。您可以获取给定用户上传的所有公开视频的列表(例如参见YouTube API to fetch all videos on a channel),然后使用videos API 获取播放列表中每个视频的统计信息,并从statistics.viewCount 获取观看次数.

    【讨论】:

      【解决方案2】:

      我会循环播放所有视频(父标签 ytd-grid-video-renderer) 然后从那里提取标题和计数。

      类似:

      allvideos = driver.find_element_by_tag_name('driytd-grid-video-renderer')
      for video in allvideos:
          title = video.find_element_by_id('video-title')
          count = video.find_element_by_xpath('//*[@id='metadata-line']/span')
          print (title, count)
      

      我没有适合您的美味汤解决方案,因为硒会为您完成大部分工作。

      在使用 driver.page_source 时要注意一点,它并没有真正返回 DOM 的完整快照,因此它可能没有按照您的想法进行操作。

      【讨论】:

        猜你喜欢
        • 2021-12-02
        • 2021-03-10
        • 2017-03-10
        • 2016-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-25
        • 2014-01-28
        相关资源
        最近更新 更多