Getting The Title of a Youtube Video Using Python/Selenium

一笑奈何 提交于 2019-12-24 19:57:41

问题


I am trying to scrape the title of a youtube video (https://www.youtube.com/watch?v=MBBtxuHoV_g) with the following python script. When I run my current code:

driver = webdriver.Chrome()
driver.get("https://www.youtube.com/watch?v=MBBtxuHoV_g")

element = WebDriverWait(driver, 10).until(
     EC.presence_of_element_located((By.CLASS_NAME,"ytd-video-primary- 
info-renderer")))
print(element.text)

The output gives me

 Bryan Cranston, Kanye West, Will Smith SHOCKED by Magician David Blaine
 458,317 views
 3.5K
 76
 SHARE

How do I change my code so it just returns the title of the video? Any help is much appreciated!


回答1:


If you only want to get that title without using any hardcoded index then the following should work:

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=MBBtxuHoV_g")
wait = WebDriverWait(driver, 10)

element = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"h1.title yt-formatted-string"))).text
print(element)
driver.quit()

Result:

Bryan Cranston, Kanye West, Will Smith SHOCKED by Magician David Blaine


来源:https://stackoverflow.com/questions/51032139/getting-the-title-of-a-youtube-video-using-python-selenium

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!