简体   繁体   中英

How can you completely remove HTML tags containing a class in python?

I have a web scraper that pulls articles from CNN, FOX, and BBC in BeautifulSoup. Then after some preprocessing, I return raw articles to an API. However, I cannot figure out how to completely remove HTML tags that contain an annoying class in Python. I tried lxml cleaner but and I can remove tags, but not only the tags which contain a certain class.

If in this example I am trying to remove "help", I would like a script that would turn HTML that looks like this:

<p class="help">Here are some tips which are useful</p>
<p> Welcome to webscraping 101 </p>
<p class="help>These are the tips </p>

into this:

<p> Welcome to webscraping 101 </p>

To remove all tags under the help class, you can use the .decompose() method:

removes a tag from the tree, then completely destroys it and its contents

for tag in soup.find_all("p", class_="help"):
    tag.decompose()

print(soup.prettify())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM