【问题标题】:How can I get a YouTube video upload date?如何获取 YouTube 视频上传日期?
【发布时间】:2021-09-09 21:15:10
【问题描述】:

我一直在尝试使用 Python 中的 Selenium 获取 YouTube 视频的上传日期(如下图所示)。

我的代码如下:

! pip install selenium
from selenium import webdriver
! pip install beautifulsoup4
from bs4 import BeautifulSoup

driver = webdriver.Chrome('D:\chromedrive\chromedriver.exe')
driver.get("https://www.youtube.com/watch?v=CoR72I5BGUU")
soup = BeautifulSoup(driver.page_source, 'lxml')

upload_date=driver.find_elements_by_xpath('//*[@id="info-strings"]/yt-formatted-string')

print(upload_date)

但是,无论我使用upload_date=soup.findAll('span', class_='style-scope ytd-grid-video-renderer') 还是upload_date=driver.find_elements_by_xpath('//*[@id="info-strings"]/yt-formatted-string'),它都不起作用。

如果有人知道问题出在哪里,请帮助我。

【问题讨论】:

    标签: python selenium beautifulsoup youtube


    【解决方案1】:

    要获取“日期”,您可以使用 CSS 选择器 #info-strings yt-formatted-string,它将选择 HTML ID info-strings,然后选择 info-strings 标记。

    此外,您应该等待页面正确加载,然后再尝试使用 WebDriverWait 抓取“日期”(需要额外的导入,请参阅代码示例)。

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    
    driver = webdriver.Chrome()
    driver.get("https://www.youtube.com/watch?v=CoR72I5BGUU")
    
    # Waits 20 seconds for the "date" the appear on the webpage
    date = WebDriverWait(driver, 20).until(
        EC.visibility_of_element_located(
            (By.CSS_SELECTOR, "#info-strings yt-formatted-string")
        )
    )
    
    print(date.text)
    
    driver.quit()
    

    输出:

    Jan 25, 2018
    

    另见:

    【讨论】:

      【解决方案2】:

      你可以试试下面的CSS_SELECTOR

      span#dot+yt-formatted-string[class$='ytd-video-primary-info-renderer']
      

      代码:

      upload_date = driver.find_element_by_css_selector("span#dot+yt-formatted-string[class$='ytd-video-primary-info-renderer']")
      print(upload_date.text)
      

      【讨论】:

        猜你喜欢
        • 2010-12-14
        • 2019-05-17
        • 1970-01-01
        • 2019-11-27
        • 2016-02-05
        • 1970-01-01
        • 2021-01-15
        • 2014-04-10
        • 2012-01-20
        相关资源
        最近更新 更多