You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium Chrome WebDriver获取YouTube悬停文本问题求助

解决YouTube精确播放量与发布日期爬取问题

核心实现方案

YouTube的精确播放量、发布日期数据,要么直接存储在目标元素的title属性中,要么需要模拟鼠标悬停触发tooltip后读取内容,以下是两种可行的WebDriver实操方案:

方案1:直接读取元素title属性

多数场景下,YouTube的播放量、发布日期元素自带包含精确数据的title属性,无需触发悬停:

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("你的目标视频URL")

# 定位播放量元素(选择器需根据实际页面调整)
view_count_elem = driver.find_element(By.CSS_SELECTOR, "span.view-count.style-scope.ytd-video-view-count-renderer")
exact_views = view_count_elem.get_attribute("title")

# 定位发布日期元素(选择器需根据实际页面调整)
publish_date_elem = driver.find_element(By.CSS_SELECTOR, "div#info-strings yt-formatted-string")
exact_date = publish_date_elem.get_attribute("title")

print(f"精确播放量: {exact_views}")
print(f"精确发布日期: {exact_date}")

driver.quit()

方案2:模拟悬停读取tooltip内容

如果title属性不存在,需通过鼠标悬停触发tooltip,再提取内容:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome()
driver.get("你的目标视频URL")

# 定位信息容器元素(选择器需根据实际页面调整)
target_elem = driver.find_element(By.CSS_SELECTOR, "div#info-strings.style-scope.ytd-video-primary-info-renderer")

# 模拟鼠标悬停
actions = ActionChains(driver)
actions.move_to_element(target_elem).perform()

# 定位tooltip元素(YouTube tooltip通常带类名yt-tooltip-text)
tooltip_elem = driver.find_element(By.CSS_SELECTOR, "div.yt-tooltip-text.style-scope.ytd-tooltip-renderer")
tooltip_content = tooltip_elem.text

# 拆分播放量与发布日期(按实际tooltip文本格式调整)
view_count, publish_date = tooltip_content.split("\n")
print(f"精确播放量: {view_count}")
print(f"精确发布日期: {publish_date}")

driver.quit()

关键注意事项

  • YouTube页面元素选择器可能随版本更新变化,需用浏览器开发者工具(F12)实时定位最新选择器
  • 页面加载存在延迟时,需添加显式等待避免元素未加载完成报错:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 等待元素加载完成,超时时间10秒
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "目标元素选择器")))
  • 测试爬取需遵守YouTube的robots协议,避免高频请求导致IP被限制

内容的提问来源于stack exchange,提问作者bloohblahguy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 04:05:03