我正在尝试使用以下python脚本抓取youtube视频(https://www.youtube.com/watch?v=MBBtxuHoV_g)的标题。 当我运行当前代码时:
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
如何更改代码,使其仅返回视频的标题?任何帮助深表感谢!
答案 0 :(得分:1)
如果您只想获取该标题而不使用任何硬编码的索引,则应执行以下操作:
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