Rik*_*hah 24 python beautifulsoup python-2.7
我想div从soup对象中删除特定的.
我正在使用python 2.7和bs4.
根据我们可以使用的文档div.decompose().
但这会删除所有的div.如何删除div特定类?
lem*_*ead 41
当然,你可以select,find或find_all将div在通常的方式兴趣s,然后叫decompose()上这些div.
例如,如果要删除所有带有类的div sidebar,可以使用
# replace with `soup.findAll` if you are using BeautifulSoup3
for div in soup.find_all("div", {'class':'sidebar'}):
div.decompose()
Run Code Online (Sandbox Code Playgroud)
如果你想删除一个特定的div id,比如说main-content,你可以用
soup.find('div', id="main-content").decompose()
Run Code Online (Sandbox Code Playgroud)
这将有助于您:
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
Run Code Online (Sandbox Code Playgroud)
输出:
<a>This is not div <div class="1">This is div 1</div></a>
Run Code Online (Sandbox Code Playgroud)
如果有帮助,请告诉我
希望对您有所帮助:
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)
Run Code Online (Sandbox Code Playgroud)