首页 > 解决方案 > 使用 BeautifulSoup,我可以在标签之间获取带有其他字符串的文本以将它们分开吗?

问题描述

所以,我一直在用 BeautifulSoup 进行爬行,但我遇到了一些乱七八糟的 html 标签。

这是一个例子:

<html>
    <body>
        <p>Hey</p>
        <div>
            <div>
                <span class="date">0817</span>
            </div>
        </div>
        <p>I want all of those</p>
        <div>
            <div>
                <p>But I want to get those separately</p>
            <div>
        </div>
        <p>Hope this work</p>
    </body>
</html>

所以如果我使用这样的代码:

soup = BeautifulSoup(html,'html.parser')
body = soup.find("body")
print(body.text)

我可能会得到这个:

"Hey0817I want all of thoseBut I want to get those separatelyHope this work"

问题是,我可以得到那些带有一些字符串作为分隔符的文本吗?分隔其他标签之间的东西的分隔符如:

"@@@Hey@@@0817@@@Iwant all of those@@@But I want to get those separately@@@Hope this work"
or
"Hey@@@0817@@@Iwant all of those@@@But I want to get those separately@@@Hope this work@@@"
or
"Hey@@@0817@@@Iwant all of those@@@But I want to get those separately@@@Hope this work"

这样我以后就可以通过“@@@”将这些文本与其他代码分开?或者有没有做类似事情的周边?任何建议都会很有帮助。感谢您的关注和时间!希望你能给我解惑。

标签: htmlpython-3.xbeautifulsoup

解决方案


如果你想要一个列表,你可以使用:

item_text = [t.text for t in body.find_all()]

如果你真的想要分隔符:

body.get_text('@@@')


推荐阅读