How to mute all sounds in chrome webdriver with selenium

后端 未结 3 1278
时光取名叫无心
时光取名叫无心 2021-02-07 00:12

I want to write a script in which I use selenium package like this:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get(\"https://www.youtube.         


        
相关标签:
3条回答
  • 2021-02-07 00:20

    use javascript to mute sounds like this

    code py

    watch_video_js= """
               let video = document.querySelector('video')
               video.muted = true
               video.play()
          """
    driver.execute_script(watch_video_js)
    
    0 讨论(0)
  • 2021-02-07 00:21

    For those who are searching for firefox solution this worked for me. I hope it will help others.

    from selenium import webdriver
    profile = webdriver.FirefoxProfile()
    profile.set_preference("media.volume_scale", "0.0")
    driver = webdriver.Firefox(firefox_profile=profile)
    
    0 讨论(0)
  • 2021-02-07 00:36

    Not sure if you can, generally for any page, do it after you have opened the page, but you can mute all the sound for the entire duration of the browser session by setting the --mute-audio switcher:

    from selenium import webdriver
    
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument("--mute-audio")
    
    driver = webdriver.Chrome(chrome_options=chrome_options)
    driver.get("https://www.youtube.com/watch?v=hdw1uKiTI5c")
    

    Or, you can mute the HTML5 video player directly:

    video = driver.find_element_by_css_selector("video")
    driver.execute_script("arguments[0].muted = true;", video)
    

    You might need to add some delay before that to let the video be initialized before muting it. time.sleep() would not be the best way to do it - a better way is to subscribe to the loadstart media event - the Python implementation can be found here.

    To summarize - complete implementation:

    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 import webdriver
    
    driver = webdriver.Chrome()
    driver.set_script_timeout(10)
    
    driver.get("https://www.youtube.com/watch?v=hdw1uKiTI5c")
    
    # wait for video tag to show up
    wait = WebDriverWait(driver, 5)
    video = wait.until(EC.visibility_of_element_located((By.TAG_NAME, 'video')))
    
    # wait for video to be initialized
    driver.execute_async_script("""
        var video = arguments[0],
            callback = arguments[arguments.length - 1];
    
        video.addEventListener('loadstart', listener);
    
        function listener() {
            callback();
        };
    """, video)
    
    # mute the video
    driver.execute_script("arguments[0].muted = true;", video)
    
    0 讨论(0)
提交回复
热议问题