从 BeautifulSoup4 (python) 的主汤中删除特定标签
这就是我尝试过的 - 看看 soup.div.decompose(),我也尝试过 soup.elements.div.decompose()。另外,这是使用 DataTables 中的内容,这是我第一次使用它,所以如果有更好的方法来实现我正在做的事情,请告诉我!提前致谢!
import bs4
with open('MapPage.html', 'r', encoding="utf8") as f:
txt = f.read()
soup = bs4.BeautifulSoup(txt,"html5lib")
elements = soup.find_all('tr')
elements.pop(0)
def DeleteData(msgID):
for div in elements:
ID = div.find('a').contents[0]
if int(msgID)==int(ID):
soup.div.decompose()
return
print('Failed to delete data from', msgID)
我希望我能够再次将汤写入“MapPage.html”。产生错误 AttributeError: 'NoneType' object has no attribute 'decompose'
。 这是打印 div
时的输出: (链接到 html 文件)
This is what i have tried - look at soup.div.decompose(), I also tried soup.elements.div.decompose(). Also this is using content from DataTables and this my first time using it so if there's a better way to achieve what i'm doing please tell me! Thanks in advace!
import bs4
with open('MapPage.html', 'r', encoding="utf8") as f:
txt = f.read()
soup = bs4.BeautifulSoup(txt,"html5lib")
elements = soup.find_all('tr')
elements.pop(0)
def DeleteData(msgID):
for div in elements:
ID = div.find('a').contents[0]
if int(msgID)==int(ID):
soup.div.decompose()
return
print('Failed to delete data from', msgID)
I'm hoping i'll be able to then just write the soup to the 'MapPage.html' again. The error AttributeError: 'NoneType' object has no attribute 'decompose'
is produced.
This is the output when printing div
:
(Link to html file)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我理解正确,您喜欢
decompose()
< tr>
,其中包含其< a>
中的特定值。主要问题是您尝试执行
soup.div.decompose()
您喜欢decompose()
first< div> 汤对象。
只需使用:
甚至更好地将变量名称更改为无标签名称:
示例
If I understand right, you like to
decompose()
the<tr>
that contains a specific value in its<a>
.Main issue is that you try to perform
soup.div.decompose()
what means, that you like todecompose()
first<div>
of soup object.Simply use:
or even better change your variable name to a none tag name:
Example