使用beautifulsoup删除p标签内的脚本标签

iLo*_*ase 4 html python beautifulsoup html-parsing

我编写了一个代码,以便从段落中提取内容

from bs4 import BeautifulSoup
from bs4 import BeautifulSoup, NavigableString
import re


soup = BeautifulSoup(open('MUFC.html'))
a_tag = soup.find_all('p')
#print(a_tag)
for x in a_tag:
    print(x.get_text())
Run Code Online (Sandbox Code Playgroud)

但是p标签内部有一些脚本标签

就像是

<p>
<script>
.....
</script>
</p>
Run Code Online (Sandbox Code Playgroud)

这是我不想要的.我们可以放一些条件以忽略get_text()方法的标签吗?

ale*_*cxe 6

首先,删除所有script标签,然后获取文本:

soup = BeautifulSoup(open('MUFC.html'))

for script in soup.find_all('script'):
    script.extract()

paragraphs = soup.find_all('p')
for paragraph in paragraphs:
    print(paragraph.get_text(strip=True))
Run Code Online (Sandbox Code Playgroud)