python 和 selenium 的 YouTube 自动化

YouTube automation with python and selenium

我想用 selenium 和 python 完全自动化 youtube。完成以下任务。问题出在第 4 点和第 6 点。如何处理它们?

  1. 打开 youtube

  2. 搜索任何视频

  3. 播放任何视频

  4. 暂停视频

  5. 喜欢不喜欢视频。

  6. 播放下一个视频

     driver = webdriver.Chrome()
     driver.get('https://www.youtube.com/')
    
     Search_Box = driver.find_element_by_xpath('//*[@id="search"]')   #search bar
     speak("opend sir what shoud i search ?")
     query=takecommand().lower()
     # query=input('data ?') 
     Search_Box.send_keys(query)
     Search_Button=driver.find_element_by_xpath('//*[@id="search-icon-legacy"]') #clicked search button
     Search_Button.click()
     speak("searched now which one ?")
    
    
     query=takecommand().lower()
     # query=input('data ?')
     if "first" in query:
         video_number = 1
         select_video1=driver.find_element_by_xpath(f"(//a[@id='video-title'])[{video_number}]").click()
         # select_video1.click()
     elif 'second' in query:
         video_number = 2
         select_video2=driver.find_element_by_xpath(f"(//a[@id='video-title'])[{video_number}]").click()
         time.sleep(5)
         speak('pausing video')
         select_video2=driver.find_element_by_css_selector('movie_player > div.ytp-chrome-bottom > div.ytp-chrome-controls > div.ytp-left-controls > button').click()  #this was for pause,but didnt worked here
    

要播放或暂停视频,您可以单击位于以下位置的播放/暂停按钮 css_selectorbutton.ytp-play-button
要转到下一个视频,请单击以下元素 a.ytp-next-button。又是 css-selector

试试这些...

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

# won't work unless you are logged in
like_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"(//yt-icon[@class='style-scope ytd-toggle-button-renderer'])[4]")))
like_btn.click()

# won't work unless you are logged in
dislike_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"(//yt-icon[@class='style-scope ytd-toggle-button-renderer'])[5]")))
dislike_btn.click()

pause_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//button[@title='Pause (k)']")))
pause_btn.click()

# comment out to test pause btn, otherwise it happens so fast you don't notice
play_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//button[@title='Play (k)']")))
play_btn.click()

mute_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//button[@aria-label='Mute (m)']")))
mute_btn.click()

# comment out to test mute_btn, otherwise it happens so fast you don't notice it
unmute_btn = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//button[@aria-label='Unmute (m)']")))
unmute_btn.click()