如何使用BeautifulSoup查找HTML页面中<p>元素内的所有文本

rar*_*777 1 python unicode beautifulsoup html-parsing

我需要在Python中使用BeautifulSoup查找HTML文件中段落元素内的所有可见标记.
例如,
<p>Many hundreds of named mango <a href="/wiki/Cultivar" title="Cultivar">cultivars</a> exist.</p>
应该返回:
Many hundreds of cultivars exist.

PS某些文件包含需要提取的Unicode字符(印地语).
任何想法如何做到这一点?

sil*_*zzo 6

以下是使用 BeautifulSoup 的方法。这将删除任何不在 VALID_TAGS 中的标签,但保留已删除标签的内容。

from BeautifulSoup import BeautifulSoup

VALID_TAGS = ['div', 'p']

soup = BeautifulSoup(value)

for tag in soup.findAll('p'):
    if tag.name not in VALID_TAGS:
        tag.replaceWith(tag.renderContents())

print soup.renderContents()
Run Code Online (Sandbox Code Playgroud)

参考