使用 BeautifulSoup 删除具有特定 class 的 div
Deleting a div with a particlular class using BeautifulSoup
我想从 soup
对象中删除特定的 div
。
我正在使用 python 2.7
和 bs4
。
根据文档我们可以使用 div.decompose()
。
但这会删除所有 div
。如何删除具有特定 class 的 div
?
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>
当然,您可以 select
, find
, or find_all
the div
s of interest in the usual way, and then call decompose()
那些 div。
例如,如果你想用 class 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()
这将帮助您:
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>
如果有帮助请告诉我
希望对您有所帮助:
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)
我想从 soup
对象中删除特定的 div
。
我正在使用 python 2.7
和 bs4
。
根据文档我们可以使用 div.decompose()
。
但这会删除所有 div
。如何删除具有特定 class 的 div
?
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>
当然,您可以 select
, find
, or find_all
the div
s of interest in the usual way, and then call decompose()
那些 div。
例如,如果你想用 class 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()
这将帮助您:
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>
如果有帮助请告诉我
希望对您有所帮助:
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)