<p>不确定是否可以(通常对于任何页面)在打开页面后执行此操作,但可以通过设置<a href="http://peter.sh/experiments/chromium-command-line-switches/#mute-audio" rel="noreferrer">^{<cd1>}</a>切换器在整个浏览器会话期间将所有声音静音:</p>
<pre><code>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")
</code></pre>
<hr/>
<p>或者,您可以<a href="https://stackoverflow.com/q/6376450/771848">mute the HTML5 video player directly</a>:</p>
<pre><code>video = driver.find_element_by_css_selector("video")
driver.execute_script("arguments[0].muted = true;", video)
</code></pre>
<p>您可能需要在此之前添加一些延迟,以便在禁用视频之前对其进行初始化。<code>time.sleep()</code>不是最好的方法-更好的方法是订阅<a href="https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events" rel="noreferrer">^{<cd3>} media event</a>-可以找到Python实现<a href="https://stackoverflow.com/a/28438996/771848">here</a>。</p>
<p>总结-完成实施:</p>
<pre><code>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)
</code></pre>