Use Python to extract comments from HTML source and remove comments

Source: Internet
Author: User

When you encounter a programming problem, you must first think of simplifying it, simplifying it to a simple problem, writing the simplest code to solve it, and paying only the simplest test cost.

Simple HTML Source:

1<!--The loneliest number--> <a>2<!--Can be as bad as one--><b>3


Extract the comments from the preceding code:

From BS4 import beautifulsoup, Commentsoup = BeautifulSoup ("" "1<!--the loneliest number--> &L t;a>2<!--Can is as bad as one--><b>3 "" ") Comments = Soup.findall (Text=lambda text:isinstance (text, Comment))) for Comment in Comments:print Comment

Output Result:

The loneliest Numbercan is as bad as one

Remove the comments from the above HTML code:

From BS4 import beautifulsoup, Commentsoup = BeautifulSoup ("" "1<!--the loneliest number--> &L t;a>2<!--Can is as bad as one--><b>3 "" ") Comments = Soup.findall (Text=lambda text:isinstance (text, Comment)) [Comment.extract () for Comment in Comments]print soup

Output Result:

1<a>2<b>3</b></a>


Reference:

1. How to find the comment tags <!--...--> with BeautifulSoup?

2, BeautifulSoup documentation #Removing elements








Use Python to extract comments from HTML source and remove comments

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.