我正在尝试使用 Selenium 和 python 从 YT 获取一些信息。代码看起来没问题,但是它没有在控制台中打印输出。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
driver = webdriver.Edge()
driver.get("https://www.youtube.com/@CorporateMusician")
driver.maximize_window()
videos= driver.find_elements(By.CLASS_NAME,'style-scope ytd-rich-grid-renderer')
for video in videos:
title= video.find_element(By.XPATH,'//*[@id="video-title"]').text,
views= video.find_element(By.XPATH,'//*[@id="metadata-line"]/span[1]').text,
posted=video.find_element(By.XPATH,'//*[@id="metadata-line"]/span[2]').text
print(title)
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.Edge()
driver.get("https://www.youtube.com/@CorporateMusician")
driver.maximize_window()
# Wait for the videos to load
wait = WebDriverWait(driver, 10) # Waiting for up to 10 seconds
videos = wait.until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'style-scope ytd-rich-grid-renderer')))
for video in videos:
try:
title = video.find_element(By.XPATH, '//*[@id="video-title"]').text
views = video.find_element(By.XPATH, '//*[@id="metadata-line"]/span[1]').text
posted = video.find_element(By.XPATH, '//*[@id="metadata-line"]/span[2]').text
print(title, views, posted)
except Exception as e:
print(f"Error fetching data: {e}")
driver.quit()
如果代码在到达 print(title) 之前遇到异常,则不会将任何内容打印到控制台。考虑添加一个 try-except 块来捕获任何异常并打印它们。