【发布时间】:2015-11-10 21:25:31
【问题描述】:
我想从soup 对象中删除特定的div。
我正在使用python 2.7 和bs4。
根据文档,我们可以使用div.decompose()。
但这会删除所有div。如何删除具有特定类的div?
【问题讨论】:
标签: python python-2.7 beautifulsoup
我想从soup 对象中删除特定的div。
我正在使用python 2.7 和bs4。
根据文档,我们可以使用div.decompose()。
但这会删除所有div。如何删除具有特定类的div?
【问题讨论】:
标签: python python-2.7 beautifulsoup
当然,您可以按照通常的方式只 select、find 或 find_all 感兴趣的 divs,然后在这些 div 上调用 decompose()。
例如,如果你想删除所有类 sidebar 的 div,你可以这样做
# replace with `soup.findAll` if you are using BeautifulSoup3
for div in soup.find_all("div", {'class':'sidebar'}):
div.decompose()
如果您想删除具有特定 id 的 div,例如 main-content,您可以使用
soup.find('div', id="main-content").decompose()
【讨论】:
elem.string.replace_with。另见this answer
这将对您有所帮助:
from bs4 import BeautifulSoup
markup = '<a>This is not div <div class="1">This is div 1</div><div class="2">This is div 2</div></a>'
soup = BeautifulSoup(markup,"html.parser")
a_tag = soup
soup.find('div',class_='2').decompose()
print a_tag
输出:
<a>This is not div <div class="1">This is div 1</div></a>
如果有帮助请告诉我
【讨论】:
a_tag 分配了一个值,然后修改了soup,但打印了a_tag。?我无法让它工作。
希望对您有所帮助:
from bs4 import BeautifulSoup
from bs4.element import Tag
markup = '<a>This is not div <div class="1">This is div 1</div><div class="2">This is div 2</div></a>'
soup = BeautifulSoup(markup,"html.parser")
for tag in soup.select('div.1'):
tag.decompose()
print(soup)
【讨论】:
from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup('<body><div>1</div><div class="comment"><strong>2</strong></div></body>')
>>> for div in soup.findAll('div', 'comment'):
... div.extract()
...
<div class="comment"><strong>2</strong></div>
>>> soup
<body><div>1</div></body>
【讨论】: