使用 Python/Selenium 获取 Youtube 视频的标题 [英] Getting The Title of a Youtube Video Using Python/Selenium

查看:39
本文介绍了使用 Python/Selenium 获取 Youtube 视频的标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试抓取 youtube 视频的标题 (https://www.youtube.com/watch?v=MBBtxuHoV_g) 和以下 python 脚本.当我运行当前代码时:

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)

输出给了我

 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!

推荐答案

如果您只想在不使用任何硬编码索引的情况下获得该标题,那么以下应该有效:

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()

结果:

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

这篇关于使用 Python/Selenium 获取 Youtube 视频的标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆