如何通过标记匹配删除元素

2024-04-26 01:25:42 发布

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

我想从存储html的变量中删除由特定元素/类包围的部分,但我不知道如何删除。你知道吗

例如,以下html文档存储在变量“content”中

<div class="content">
  <h1>content</h1>
  <p>content<p>
  <p>content</p>
<div>

<!-- want to delete from here -->
<div class="Footer">
 <div class=Footer-item>
  ...
  ...

 </div>
</div>

我试着实现如下

from urllib.parse import urlparse

newcontent = content.find("div", {"class":"Footer"}).extract()

但是,发生了以下错误

TypeError: slice indices must be integers or None or have an __index__ method

如果你有好的解决办法,请告诉我。你知道吗


Tags: ortofrom文档div元素herehtml
1条回答
网友
1楼 · 发布于 2024-04-26 01:25:42

您可以使用BeautifulSoup解析html文档。你知道吗

from bs4 import BeautifulSoup

markup = "......<div class='footer'> ...</div>"
soup = BeautifulSoup(markup,"html.parser")
other_tags = soup

soup.find('div',class_='footer').decompose()

print (other_tags)

相关问题 更多 >