【问题标题】:Scrape From Youtube从 Youtube 抓取
【发布时间】:2020-11-25 15:34:52
【问题描述】:

我正在尝试从代码中的链接中抓取视频标题。

基本上是想滚动+刮。

我的代码运行了,但它刮掉了页面的一半,而不是刮掉剩下的一半,而是重复前半部分。

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)
content=driver.page_source.encode('utf-8').strip()
soup=BeautifulSoup(content,'lxml')
SCROLL_PAUSE_TIME = 2

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

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)
    titles = soup.findAll('a', id='video-title')
    for title in titles:
        print(title.text)

    # 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

【问题讨论】:

标签: python selenium xpath


【解决方案1】:

我认为问题在于你在 if 循环中,它可能 new_height 可以人为地等于最后一个高度,这就是我会看的地方

【讨论】:

    【解决方案2】:

    我会简单地找到您想要滚动到的元素并使用 move_to_element

    https://www.geeksforgeeks.org/move_to_element-method-action-chains-in-selenium-python/

    # get the last video element
    element = driver.find_elements_by_id("video-title")[-1]
      
    # create action chain object 
    action = ActionChains(driver) 
      
    # perform the operation 
    action.move_to_element(element)
    

    这应该足以触发您的电子管上的无限滚动。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-28
      • 2019-07-25
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2022-11-29
      • 2020-10-09
      • 2021-07-24
      相关资源
      最近更新 更多