How can I click the "SORT BY" button and select "Newest first" item on YouTube video page?

Viewed 154

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). enter image description here 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.

2 Answers

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

I think your code should do something like this:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

wait = WebDriverWait(driver, 20)
actions = ActionChains(driver)

sort_comments_xpath = "//*[@aria-label='Sort comments']"
newest_first_xpath = "//div[contains(text(),'Newest first')]"

sort_comments = wait.until(EC.presence_of_element_located((By.XPATH, sort_comments_xpath)))
actions.move_to_element(sort_comments).build().perform()
time.sleep(0.5)
sort_comments.click()

newest_first = wait.until(EC.visibility_of_element_located((By.XPATH, newest_first_xpath))).click()

Wait until sort comments element appears, scroll to it, click it.
Wait until newest first option appears, click on it.

Related