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

如何用BeautifulSoup获取div中<br/>标签后文本并解决属性错误?

解决BeautifulSoup获取歌词时的AttributeError及
标签处理问题

嘿,我来帮你搞定这两个问题!先拆解你遇到的问题,再一步步给出解决方案:

1. 先搞定AttributeError: 'list' object has no attribute 'get_text'

你用soup1.select()获取的container是一个元素列表——哪怕页面上只有一个匹配元素,select()返回的都是列表类型。所以你直接给列表调用get_text()肯定会报错,得先取出列表里的具体元素,比如取第一个匹配项:container[0]。

更简洁的方式是用select_one(),它直接返回匹配到的第一个元素(不是列表),能省掉取索引的步骤。

2. 跳过
标签,获取分行的歌词

BeautifulSoup的get_text()方法自带separator参数,专门用来处理这类换行标签。你只需要把separator设为'\n',<br/>就会被自动替换成换行符,歌词就能按原页面的分行格式显示了。

另外,我发现你代码里的URL拼接有个小bug:

self.url = "https://search.azlyrics.com/search.php?q=let+me+love+you{}".format(self.text)

这里多了固定的let+me+love+you,会导致搜索关键词混乱,应该改成直接拼接用户输入的内容:

self.url = "https://search.azlyrics.com/search.php?q={}".format(self.text)

修改后的完整代码

from bs4 import BeautifulSoup
import requests

class EpicLyricFinderApp:
    def __init__(self):
        self.text = '+'.join(input('Enter song name and also include singer: ').split(' '))
        # 修复URL拼接错误
        self.url = "https://search.azlyrics.com/search.php?q={}".format(self.text)
        self.lyrics = ''
        self.app()

    def app(self):
        req = requests.get(self.url).content
        soup = BeautifulSoup(req, 'html.parser')
        links = [link['href'] for link in soup.select('.text-left a')]
        
        # 增加容错:防止搜索不到结果时links为空报错
        if not links:
            print("No lyrics found for your query!")
            return
            
        req1 = requests.get(links[0]).content
        soup1 = BeautifulSoup(req1, 'html.parser')
        # 用select_one直接获取单个元素,避免列表操作
        container = soup1.select_one('body > div.container.main-page > div > div.col-xs-12.col-lg-8.text-center > div:nth-child(10)')
        if container:
            # 用separator='\n'替换<br/>为换行,strip()去除首尾冗余空白
            lyrics_text = container.get_text(separator='\n').strip()
            print(lyrics_text)
        else:
            print("Couldn't locate the lyrics container on the page!")

if __name__ == '__main__':
    app = EpicLyricFinderApp()

额外优化说明

  • 加了两处容错判断:检查搜索结果链接是否为空、检查歌词容器是否存在,避免程序因找不到元素直接崩溃。
  • 用strip()去除了文本首尾多余的空白字符,让歌词显示更整洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:41:38