beautifulsoup删除所有内部javascript

beautifulsoup remove all the internal javascript

本文关键字:内部 javascript 删除 beautifulsoup      更新时间:2023-09-26

下面是一个简单的BeautifulSoup代码,它有两个内部JavaScript(不要责怪JavaScript,它只是为了测试目的(。

from bs4 import BeautifulSoup
html = """
<html><head><title>The Dormouse's story</title>
<script>
var x = 5;
var y = 6;
document.getElementById("demo").innerHTML = x + y;
//document.getElementById("demo").innerHTML = x;
//document.getElementById("demo").innerHTML = y;
</script>
<script>
var x = 5;
var y = 6;
document.getElementById("demo").innerHTML = x + y;
//document.getElementById("demo").innerHTML = x;
//document.getElementById("demo").innerHTML = y;
</script>
</head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
soup = BeautifulSoup(html)
soup.script.decompose()
print soup.prettify()

当我运行此代码时,它只从文档(Dom树(中删除了一个<script>...</script>,但没有删除所有其他脚本标记。我们如何删除文档中存在的所有<script>, <style>(内部和内联(标记

您需要找到所有应用的script标记;你只找了第一个。使用soup.find_all():

for script in soup.find_all('script', src=False):
    script.decompose()

这会发现所有不<script>标记都具有src属性。

for element in soup.findAll('script'):
            element.extract()

另一种选择是,您可以将'script'替换为['script', 'style']来消除样式。

删除soup:中的所有<script><style>标签

 for tag in soup.find_all("script"): soup.script.decompose()
 for tag in soup.find_all("style"): soup.style.decompose()