【问题标题】:How to get text after <br/> tag in div?如何在div中的<br/>标签后获取文本?
【发布时间】:2019-11-19 11:43:11
【问题描述】:

我写了一个脚本,可以在一秒钟内从互联网上下载歌词。 div 中的歌词文本,行尾带有&lt;br&gt;。当我试图通过 BeautifulSoup 获取文本时。我收到此错误:

回溯(最近一次通话最后一次):
文件“/home/rohit/Desktop/lyrics_finder.py”,第 27 行,在
app = EpicLyricFinderApp()
init
中的文件“/home/rohit/Desktop/lyrics_finder.py”,第 10 行 self.app()
应用程序中的文件“/home/rohit/Desktop/lyrics_finder.py”,第 21 行
对于我在 container.get_text():
AttributeError: 'list' 对象没有属性 'get_text'

我会尝试很多不同的方法,但我会得到这个问题的解决方案

我的代码:

from bs4 import BeautifulSoup
import os, requests, re


class EpicLyricFinderApp:
    def __init__(self):
        self.text = '+'.join(input('Enter song name and also include singer: ').split(' '))
        self.url = "https://search.azlyrics.com/search.php?q=let+me+love+you{}".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')]

        # Open another url
        req1 = requests.get(links[0]).content
        soup1 = BeautifulSoup(req1, 'html.parser')
        container = soup1.select('body > div.container.main-page > div > div.col-xs-12.col-lg-8.text-center > div:nth-child(10)')

        for i in container.get_text():
            print(i)



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

我预计:

如何在 Beautifulsoup 中跳过 &lt;br/&gt; 以获取文本。

【问题讨论】:

    标签: python python-3.x beautifulsoup formatting


    【解决方案1】:

    容器是列表对象而不是元素。这就是您收到此错误的原因。

    AttributeError: 'list' 对象没有属性 'get_text'

    你需要在迭代中获取文本。

    for i in container:
        print(i.get_text())
    

    【讨论】:

    • 非常感谢。我忘了!
    猜你喜欢
    • 1970-01-01
    • 2016-01-21
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多