Skip to content
Advertisement

Getting The Title of a Youtube Video Using Python/Selenium

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!

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement