You need to enable JavaScript to run this app. 如何用Python Selenium获取浏览器开发者工具Network面板Media请求日志
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python Selenium获取浏览器开发者工具Network面板Media请求日志

问题解决方案

一、Chrome环境下过滤.m4a音频地址

你拿到的performance日志每条都是JSON格式的字符串,只需要解析后筛选请求事件,匹配音频地址规则即可,补充代码如下:

import json
import re

# 匹配音频地址规则
audio_pattern = re.compile(r'[0-9a-f]+\.m4a', re.I)
audio_urls = []

# 解析performance日志
logs = driver.get_log('performance')
for log in logs:
    log_entry = json.loads(log['message'])['message']
    # 筛选请求发送事件
    if log_entry['method'] == 'Network.requestWillBeSent':
        req_url = log_entry['params']['request']['url']
        if audio_pattern.search(req_url) and req_url not in audio_urls:
            audio_urls.append(req_url)

print("提取到的音频地址:", audio_urls)

二、Firefox环境下的实现方案

Firefox的geckodriver原生不支持get_log('performance')接口,所以你之前的配置会报错。推荐使用selenium-wire库直接拦截所有浏览器请求,无需配置复杂的日志规则,同时兼容Chrome和Firefox。

步骤1:安装依赖

执行命令:pip install selenium-wire

步骤2:完整实现代码

import os
import time
import re
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from seleniumwire import webdriver

# 配置参数
audio_pattern = re.compile(r'[0-9a-f]+\.m4a', re.I)
options = Options()
options.headless = True
path = (os.environ['APPDATA'] + r'\Mozilla\Firefox\Profiles\Selenium').replace('\\', '/')
profile = webdriver.FirefoxProfile(path)
profile.set_preference("media.volume_scale", "0.0")

# 启动浏览器
driver = webdriver.Firefox(
    firefox_profile=profile,
    options=options
)
wait = WebDriverWait(driver, 15)

try:
    driver.get('https://music.163.com/#/song?id=32477986')
    iframe = driver.find_element(By.XPATH, '//iframe[@id="g_iframe"]')
    driver.switch_to.frame(iframe)
    # 等待播放按钮加载完成
    play_btn = wait.until(EC.visibility_of_element_located((By.XPATH, '//div[2]/div/a[1]')))
    play_btn.click()
    # 等待音频请求加载
    time.sleep(5)
    
    # 筛选音频地址
    audio_urls = []
    for req in driver.requests:
        if req.response and audio_pattern.search(req.url) and req.url not in audio_urls:
            audio_urls.append(req.url)
    print("提取到的音频地址:", audio_urls)
finally:
    driver.quit()

注意事项

  • 批量爬取时请添加合理的请求间隔,避免被反爬策略封禁
  • 提取到的音频地址存在有效期,请勿长期存储
  • 如需更高效率的批量获取,可以直接调用网易云音乐公开API获取音频地址,无需启动浏览器渲染

内容的提问来源于stack exchange,提问作者user15290516

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 22:15:08