且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 BeautifulSoup 删除具有特定类的 div

更新时间:2023-01-17 19:15:54

当然,你可以选择findfind_all 以通常的方式找到感兴趣的div,然后调用decompose() 在这些 div 上.

Sure, you can just select, find, or find_all the divs of interest in the usual way, and then call decompose() on those divs.

例如,如果您想删除所有带有 sidebar 类的 div,您可以使用

For instance, if you want to remove all divs with class sidebar, you could do that with

# replace with `soup.findAll` if you are using BeautifulSoup3
for div in soup.find_all("div", {'class':'sidebar'}): 
    div.decompose()

如果你想删除一个带有特定id的div,比如main-content,你可以用

If you want to remove a div with a specific id, say main-content, you can do that with

soup.find('div', id="main-content").decompose()