如何使用 Selenium WebDriver 在 Chrome 浏览器中静音所有声音?

seleniumautomation testingtesting tools

我们可以使用 Selenium WebDriver 在 Chrome 浏览器中静音所有声音。要静音音频,我们需要为浏览器设置参数。对于 Chrome 浏览器,我们将使用 ChromeOptions 类。

我们将创建一个 ChromeOptions 类的对象。然后使用该对象调用 addArguments 方法。接着将 --mute--audio 作为参数传递给该方法。最后,将此信息发送给驱动程序对象。

语法

ChromeOptions op = new ChromeOptions();
op.addArguments("−−mute−audio");
WebDriver d = new ChromeDriver(op);

对于 Firefox,我们将使用 FirefoxOptions 类并创建一个该类的对象。然后使用该对象调用 addPreference 方法,并将 media.volume_scale 和 0.0 作为参数传递给该方法。最后,将此信息发送给驱动程序对象。

语法

FirefoxOptions profile = new FirefoxOptions();
profile.addPreference("media.volume_scale", "0.0");
WebDriver driver = new FirefoxDriver(profile);

示例

Code Implementation for Chrome.

import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class AudioMuteChrome {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      // ChromeOptions 类的对象
      ChromeOptions op = new ChromeOptions();
      // 添加静音参数
      op.addArguments("−−mute−audio");
      // 为浏览器添加选项
      ChromeDriver driver= new ChromeDriver(op);
      driver.get("https://www.youtube.com/watch?v=WV40Rb1J−AI/");
      driver.quit();
   }
}

示例

Code Implementation for Firefox.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
public class MuteAudioFirefox{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
      "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
      // FirefoxOptions 类的实例
      FirefoxOptions profile = new FirefoxOptions();
      // 添加静音浏览器首选项
      profile.addPreference("media.volume_scale", "0.0");
      WebDriver driver = new FirefoxDriver(profile);
      driver.get("https://www.youtube.com/watch?v=WV40Rb1J−AI/");
      driver.quit();
   }
}

相关文章