gpt4 book ai didi

python - 使用 Beautiful Soup 从字符串中去除 html 标签

转载 作者:太空狗 更新时间:2023-10-30 00:52:14 28 4
gpt4 key购买 nike

有没有人有一些示例代码来说明如何使用 Python 的 Beautiful Soup 从文本字符串中去除所有 html 标签,除了一些标签?

我想去掉所有的 javascript 和 html 标签,除了:

<a></a>
<b></b>
<i></i>

还有类似的东西:

<a onclick=""></a>

感谢您的帮助——我在互联网上找不到太多用于此目的的内容。

最佳答案

import BeautifulSoup

doc = '''<html><head><title>Page title</title></head><body><p id="firstpara" align="center">This is <i>paragraph</i> <a onclick="">one</a>.<p id="secondpara" align="blah">This is <i>paragraph</i> <b>two</b>.</html>'''
soup = BeautifulSoup.BeautifulSoup(doc)

for tag in soup.recursiveChildGenerator():
if isinstance(tag,BeautifulSoup.Tag) and tag.name in ('a','b','i'):
print(tag)

产量

<i>paragraph</i>
<a onclick="">one</a>
<i>paragraph</i>
<b>two</b>

如果您只想要文本内容,可以将print(tag) 更改为print(tag.string)

如果你想从 a 标签中删除像 onclick="" 这样的属性,你可以这样做:

if isinstance(tag,BeautifulSoup.Tag) and tag.name in ('a','b','i'):
if tag.name=='a':
del tag['onclick']
print(tag)

关于python - 使用 Beautiful Soup 从字符串中去除 html 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4423953/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com