Python development "modules": BeautifulSoup

Source: Internet
Author: User

BeautifulSoup

BeautifulSoup is a module that receives an HTML or XML string, then formats it, and then passes through the method he provides to quickly find the specified element, making it easier to find the specified element in HTML or XML

1. Installation:

PIP3 Install Beautifulsoup4pip install  lxml   # python2.x

2, simple use:

From BS4 Import Beautifulsouphtml_doc = "" "

3. Labeling Method:

① name tag names

# nametag = Soup.find (' A ') # <a class= "Sister0" id= "link1" >els<span>f</span>ie</a>name = Tag.name # Get Print (name)  # atag.name = ' span ' # setting replaces the first a label for span label print (soup)

② attrs Tag Properties

# Attrstag = Soup.find (' A ') # <a class= "Sister0" id= "link1" >els<span>f</span>ie</a>attrs = Tag.attrs          # Get Print (attrs) # {' Class ': [' Sister0 '], ' id ': ' link1 '}tag.attrs = {' IK ': 123}     # Set property tag.attrs[' id '] = ' IIIII ' # change idprint (soup)

③ children All Child Tags

# child tag, just get son tag = soup.find (' A ') # <a class= "Sister0" id= "link1" >els<span>f</span>ie</a>v = Tag.childrenprint (v) # <list_iterator object at 0x02e71230>for i in V:    print (i) # els# <span>f</span ># IE

④ descendants descendants label

# get Descendants BODY = soup.find (' body ') v = body.descendantsprint (v) for I in V:    print (i)

⑤ Clear clears all the label's child labels (retains the signature) 

# clear Tab Contents tag = soup.find (' body ') tag.clear () print (soup) # 

⑥ decompose, remove all tags recursively

# recursive removal of all tags BODY = soup.find (' body ') Body.decompose () print (soup) # 

⑦ Extract Remove all tags recursively and get deleted tags

# recursively Delete all tags and get deleted tags BODY = soup.find (' body ') v = body.extract () print (soup) # 

  

 

Python development "modules": BeautifulSoup

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.