如何点击 YouTube 视频页面上的 "SORT BY" 按钮和 select "Newest first" 项?

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

作为 Python 的初学者,我一直在尝试点击 YouTube 视频页面上的“排序方式”按钮和 select“最新第一”项目(如下图所示) . 我尝试了以下代码。

! 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()

但是,driver.find_element('div#trigger.style-scope.tp-yt-paper-menu-button').click()driver.find_elements_by_css_selector('#dropdown').click() 不起作用。它一直显示 Message: invalid argument: invalid locator 的错误。 如果有人知道如何解决,请帮助我。

我认为你的代码应该做这样的事情:

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()

等到 sort comments 元素出现,滚动到它,点击它。
等到 newest first 选项出现,点击它。

试试下面的代码:

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()

进口:

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