I'm learning how to use selenium and I want to make a program that opens up youtube, searches for a video and prints the title of the first video to appear. I don't know why but it instead prints the title of the first video on youtube's homepage.
from logging import exception
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
PATH = 'C:\\Program Files (x86)\\chromedriver.exe'
driver = webdriver.Chrome(PATH)
driver.get("https://www.youtube.com/")
search = driver.find_element(By.CSS_SELECTOR, 'input#search')
search.send_keys("busqueda")
time.sleep(1)
search.send_keys(Keys.RETURN)
time.sleep(5)
try:
element = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH, '//*[@id="video-title"]')))
print("título: ", element.get_attribute("innerHTML"))
except BaseException as e:
print(e)
finally:
driver.quit()
CodePudding user response:
Please use below xpath, which will print the YouTube videos title with,
'.//a[@class = "yt-simple-endpoint style-scope ytd-video-renderer"]//yt-formatted-string[@class = "style-scope ytd-video-renderer"]'
CodePudding user response:
elem=driver.find_element(By.CSS_SELECTOR,"a#video-title yt-formatted-string.style-scope.ytd-video-renderer")
print(elem.text)
Should suffice for the first element with that selector. After you add a wait.