📜  使用Python自动化 Youtube

📅  最后修改于: 2022-05-13 01:55:15.293000             🧑  作者: Mango

使用Python自动化 Youtube

在本文中,我们将看到如何使用Python自动化Youtube

使用的模块

  • Selenium:它通过程序控制网络浏览器
  • pyttsx3:它是Python中的文本到语音转换库
  • Speech_recognition:语音识别是家庭自动化、人工智能等多种应用中的重要功能
  • pyaudio:用于在各种平台上播放和录制音频

确保您已记下 chromedriver 的下载位置(因为它在我们的Python脚本中使用)。现在下载后解压缩 zip 文件,请注意解压缩文件的文件位置,因为我们稍后在Python代码中需要它。 (您可以通过单击属性然后单击详细信息来找到该位置)。

方法

  • 导入我们已经安装的库。
  • 然后我们必须使用语音识别库来获取输入搜索查询。我们可以通过将 Speech_recognition 库的一个实例作为 sr.Recognizer() 来做到这一点。
  • 在此之后调整阈值频率并将语音输入转换为字符串。
  • 然后,主要部分进入图片,我们创建了一个函数automatedYoutube(),它可以播放来自 Youtube 的所需视频。
  • 在这个函数中,我们使用函数webdriver.Chrome() 创建我们的驱动程序实例,它以 chromedriver 的路径为参数。
  • 最后,通过右键单击检查搜索栏和 .search 按钮,找到搜索栏和搜索按钮的名称或 id 或类或 CSS 选择器。
  • 现在,只需调用automaticYoutube()函数即可查看输出。
  • 现在我们必须自动化播放/暂停按钮,我们再次使用selenium找到播放/暂停按钮的 CSS 选择器。

下面是完整的实现

Python3
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import speech_recognition as sr
import pyttsx3
import time
  
  
def automateYoutube(searchtext):
    
    # giving the path of chromedriver to selenium websriver
    path = "C:\\Users\\hp\\Downloads\\chromedriver"
  
    url = "https://www.youtube.com/"
      
    # opening the youtube in chromedriver
    driver = webdriver.Chrome(path)
    driver.get(url)
  
    # find the search bar using selenium find_element function
    driver.find_element_by_name("search_query").send_keys(searchtext)
  
    # clicking on the search button
    driver.find_element_by_css_selector(
        "#search-icon-legacy.ytd-searchbox").click()
  
    # For findding the right match search
    WebDriverWait(driver, 0).until(expected_conditions.title_contains(MyText))
  
    # clicking on the match search having same as in searched query
    WebDriverWait(driver, 30).until(
        expected_conditions.element_to_be_clickable((By.ID, "img"))).click()
  
    # while(True):
    #     pass
  
  
speak = sr.Recognizer()
try:
    with sr.Microphone() as speaky:
        
        # adjust the energy threshold based on
        # the surrounding noise level
        speak.adjust_for_ambient_noise(speaky, duration=0.2)
        print("listening...")
          
        # listens for the user's input
        searchquery = speak.listen(speaky)
          
        # Using ggogle to recognize audio
        MyText = speak.recognize_google(searchquery)
        MyText = MyText.lower()
  
except sr.RequestError as e:
    print("Could not request results; {0}".format(e))
  
except sr.UnknownValueError:
    print("unknown error occured")
  
# Calling thr function
automateYoutube(MyText)


输出: