As a beginner to Python, I've been trying to click the "SORT BY" button and select "Newest first" item on YouTube video page (Like the following picture shows).
I tried with the following code.
! pip install selenium
from selenium import webdriver
import time
driver = webdriver.Chrome('D:\chromedrive\chromedriver.exe')
driver.get("https://www.youtube.com/watch?v=ioNng23DkIM")
!pip install pynput
from pynput.mouse import Button, Controller
mouse = Controller()
mouse.scroll(0, -5)
time.sleep(1)
#click "SORT BY" button
driver.find_element('div#trigger.style-scope.tp-yt-paper-menu-button').click()
#click "Newest first" button
driver.find_elements_by_css_selector('#dropdown').click()
However, driver.find_element('div#trigger.style-scope.tp-yt-paper-menu-button').click()
and driver.find_elements_by_css_selector('#dropdown').click()
do not work. It kept showing the error of Message: invalid argument: invalid locator
.
If anyone knows how to solve it, please help me.
try below code :
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.style-scope.yt-dropdown-menu:nth-of-type(1)"))).click()
wait.until(EC.visibility_of_element_located((By.XPATH, "//div[text()='Newest first']"))).click()
Imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC