python - BeautifulSoup 删除标签属性和文本内容

标签 python beautifulsoup

我想根据网页的整体 DOM 结构来比较一些网页,而不是根据它们的特定内容。为此,我需要一个类似于标签层次结构但不包含属性或文本标签内容的表示。

基本上,我想把这样的表示变成这样

<!DOCTYPE html>
<html>
<body>

<h1 id="peter">My First Heading</h1>
<p><span style="color:red">My</span> first paragraph.</p>

<img src="peter.jpg" />

</body>
</html>

像这样的规范裸机表示:

<html><body><h1></h1><p><span></span></p><img/></body></html>

即删除所有属性,以及不是其他标签的标签内容。

我找到了一种从标签中删除属性的方法,但我在区分文本子节点和标签子节点时遇到问题。

最佳答案

作为docs说,

You can’t edit a string in place, but you can replace one string with another, using replace_with()

所以我会选择这样的东西(假设 soup 正是您发布的内容):

for e in soup.find_all(True):
    e.attrs = {}

    for i in e.contents:
        if i.string:
            i.string.replace_with('') 

我认为,如果不循环每个标签的内容,如果一个标签有多个子标签,其中一个是文本,另一个是包含文本的另一个标签(如您的示例中所示),您最终会得到一些剩余的文本<p><span style="color:red">My</span> first paragraph.</p>)。

当针对您的示例运行时:

(env) $ python strip.py                                                               
<!DOCTYPE html>

<html><body><h1></h1><p><span></span></p><img/></body></html>

(可以稍微更改一下,这样它就不会返回换行符或文档类型)

关于python - BeautifulSoup 删除标签属性和文本内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43901940/

相关文章:

python - 通过python脚本启动停止服务和关闭

Python 网络抓取工具在输入 520 个 url 时卡住。它出什么问题了?

python - 为什么我无法在Python中抓取这个链接?

python - 使用 css 样式从网站抓取数据 使用 Beautifulsoup

python - BeautifulSoup - 如何遍历 "tr"标签?

python - 设计一个 RE 来过滤单词

python - emacs 中的 gdb : python commands (py and pi)

python - 从列中提取部分值

python - 如何通过Python向Mongo对象中插入数据

Python BeautifulSoup HTML 解析获取文本