如何通过Excel VBA的Selenium EdgeDriver检测HTML音频播放结束
To automatically close the Edge browser once the audio finishes playing, you can use Selenium's ExecuteAsyncScript method to inject JavaScript that listens for the HTML5 audio ended event. Here's how to implement this in your VBA code:
Step-by-Step Implementation
Wait for the Audio Element to Be Available
First, ensure the audio element has loaded on the page before attaching the event listener to avoid runtime errors:driver.WaitUntil _ Condition:=Function(d) d.FindElementByTag("audio").IsDisplayed, _ Timeout:=10000 ' Wait up to 10 secondsInject Async JavaScript to Listen for the 'ended' Event
UseExecuteAsyncScriptto run a script that attaches an event listener to the audio element. The script will call Selenium's built-in callback once the audio ends, which signals VBA to proceed:driver.ExecuteAsyncScript _ "var audio = document.querySelector('audio');" & _ "audio.addEventListener('ended', function() {" & _ "arguments[0](); // Notify Selenium the event has fired" & _ "});"- If your page has multiple audio elements, replace
document.querySelector('audio')with a more specific selector (e.g.,document.getElementById('target-audio-id')ordocument.querySelector('.audio-player-class')).
- If your page has multiple audio elements, replace
Close the Browser
Once the async script completes (when the audio ends), callQuitto close Edge:driver.Quit
Full Example Code
Integrate the above into your existing workflow:
Sub AutoCloseAfterAudio() Dim driver As New EdgeDriver ' Initialize Edge and navigate to your audio page driver.Get "https://your-audio-page-url.com" ' Optional: Trigger playback if audio doesn't start automatically driver.FindElementByTag("audio").Click ' Wait for audio element to load driver.WaitUntil _ Condition:=Function(d) d.FindElementByTag("audio").IsDisplayed, _ Timeout:=10000 ' Wait for audio playback to finish driver.ExecuteAsyncScript _ "var audio = document.querySelector('audio');" & _ "audio.addEventListener('ended', function() {" & _ "arguments[0]();" & _ "});" ' Close the browser driver.Quit End Sub
Notes
- Timeout Handling: Add
driver.SetAsyncScriptTimeout 30000(30 seconds) beforeExecuteAsyncScriptto set a maximum wait time if you want to avoid infinite waits. - Selector Precision: Always use the most specific selector possible to target the correct audio element on your page.
内容的提问来源于stack exchange,提问作者김수연

