首页 > 解决方案 > 使用 python 从 HTML 中获取文本

问题描述

我有 HTML 数据,我想获取

标签并将其放入数据框中以进行进一步处理。

但我只想要文本中的

这些标签之间的标签:

            <div class="someclass" itemprop="text">
                    <p>some text</p>
            </div>

使用 BeautifulSoup 我可以在所有

标签很容易。但正如我所说,我不想要它,除非它在这些标签之间。

标签: pythonhtmlbeautifulsoup

解决方案


如果想要标签中的文本仅与特定类相关联,则可以使用 BeautifulSoup 指定具有以下attrs属性的特定类:

html = '''<div class="someclass" itemprop="text">
                    <p>some text</p>
            </div>'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')

tags = soup.find_all('div', attrs={'class': 'someclass'})

for tag in tags:
    print(tag.text.strip())

输出:

some text

推荐阅读