You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python下载YouTube歌曲脚本报错AttributeError: 'Response'无'html'属性如何解决?

问题解决:AttributeError: 'Response' object has no attribute 'html'

错误原因

你用requests.get()获取的Response对象本身并没有html属性——这个写法是requests-html库的专属特性,但你只导入了基础版requests库,所以触发了属性不存在的错误。要解析HTML内容,必须用专门的HTML解析工具,比如BeautifulSoup4。

修复步骤

  1. 安装依赖工具
    先安装HTML解析库和对应的解析器:

    pip install beautifulsoup4 lxml
    
  2. 修改代码并修复潜在问题
    替换原有的HTML解析逻辑,同时解决几个隐藏问题:

    • 用urllib.parse处理搜索关键词的URL编码,避免特殊字符导致请求失败
    • 替换pytube中已弃用的streams.first()方法,改用音频流专用的get_audio_only()
    • 优化YouTube搜索结果的链接提取逻辑,适配页面结构

修改后的完整代码:

import os
import sys
import requests
from urllib.parse import urlencode
from bs4 import BeautifulSoup
from pytube import YouTube

# 检查命令行参数是否正确
if len(sys.argv) != 3:
    print("用法:python download_songs.py <文件名> <文件夹名>")
    sys.exit(1)

file_name = sys.argv[1]
folder_name = sys.argv[2]

# 创建保存歌曲的文件夹
if not os.path.exists(folder_name):
    os.makedirs(folder_name)

# 读取文件中的歌曲列表
with open(file_name) as f:
    song_titles = [line.strip() for line in f if line.strip()]

# 循环下载每首歌曲
for song_title in song_titles:
    # 构造编码后的搜索URL,避免特殊字符报错
    search_params = {"search_query": f"{song_title} extended mix"}
    url = "https://www.youtube.com/results?" + urlencode(search_params)
    
    # 发送HTTP请求并检查状态
    response = requests.get(url)
    response.raise_for_status()
    
    # 解析HTML页面
    soup = BeautifulSoup(response.text, "lxml")
    
    # 提取第一个有效视频链接
    first_video_link = None
    for link in soup.find_all("a", href=True):
        if link["href"].startswith("/watch?v="):
            first_video_link = "https://www.youtube.com" + link["href"]
            break
    
    if not first_video_link:
        print(f"未找到歌曲「{song_title}」的搜索结果")
        continue
    
    # 下载音频流
    try:
        yt = YouTube(first_video_link)
        audio_stream = yt.streams.get_audio_only()
        audio_stream.download(output_path=folder_name)
        print(f"已完成:{song_title}")
    except Exception as e:
        print(f"下载「{song_title}」失败:{str(e)}")

额外提示

  • YouTube页面结构会不定期更新,如果后续出现链接提取失败,需要检查页面元素的选择器是否需要调整
  • 若pytube触发反爬报错,可尝试更新到最新版本:pip install --upgrade pytube

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 21:30:25