如何从发送给beautifulSoup类的文件中删除html元素?

2024-04-19 15:33:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python/beautifulSoup来查找特定类的div,我想从一个文件中删除整个html元素

这就是我所拥有的——

with open(url) as f:
  elementToDelete = BeautifulSoup(f.read()).find("div", {'class': 'element-that-needs-to-go'})
  removeTheElement = elementToDelete.replace('THISISWHEREIMSTUCK', '')
with open(url, 'w') as f:
  f.write(removeTheElement)

我似乎找不到合适的方法来做我想做的事


Tags: 文件divurl元素readhtmlaswith
1条回答
网友
1楼 · 发布于 2024-04-19 15:33:18

使用分解方法:

Python代码:

from bs4 import BeautifulSoup

html = '''
<div>
  <div class="element-that-needs-to-go">
  </div>
</div>
'''
soup = BeautifulSoup(html)
tag_to_remove = soup.find("div", {'class': 'element-that-needs-to-go'})
tag_to_remove.decompose()
print(soup)

演示:Here

相关问题 更多 >