Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从发送给beautifulSoup类的文件中删除html元素?_Python_Methods_Beautifulsoup - Fatal编程技术网

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

Python 如何从发送给beautifulSoup类的文件中删除html元素?,python,methods,beautifulsoup,Python,Methods,Beautifulsoup,我使用Python/beautifulSoup查找特定类的div,我想从文件中删除整个html元素 这就是我所拥有的-- 我似乎找不到正确的方法来做我想做的事。使用分解方法: Python代码: from bs4 import BeautifulSoup html = ''' <div> <div class="element-that-needs-to-go"> </div> </div> ''' soup = BeautifulSou

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

这就是我所拥有的--


我似乎找不到正确的方法来做我想做的事。

使用分解方法:

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)
从bs4导入美化组
html=“”
'''
soup=BeautifulSoup(html)
tag_to_remove=soup.find(“div”,{'class':'element that needs to go'})
标记要删除的对象。分解()
印花(汤)

演示:

谢谢!这帮了大忙。但是,当我再次尝试在文件中写入“soup”时:“'with open(url,'w')作为f:f.write(removeTheElement)'”我得到了以下错误:回溯(最近一次调用):文件“import.py”,第97行,在标题中。write(removeFundLink)TypeError:需要字符缓冲区对象哦,天哪,你是我的英雄。非常感谢。快凌晨4点了,我可以睡觉了。
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)