The method of python to html filtering

  • 2021-01-02 21:53:59
  • OfStack

As shown below:


## filter HTML In the label 
# will HTML Remove tags and other information from 
#@param htmlstr HTML string .
def filter_tags(htmlstr):
 # To filter CDATA
 re_cdata=re.compile('//<!\[CDATA\[[^>]*//\]\]>',re.I) # matching CDATA
 re_script=re.compile('<\s*script[^>]*>[^<]*<\s*/\s*script\s*>',re.I)#Script
 re_style=re.compile('<\s*style[^>]*>[^<]*<\s*/\s*style\s*>',re.I)#style
 re_br=re.compile('<br\s*?/?>')# Processing line 
 re_h=re.compile('</?\w+[^>]*>')#HTML The label 
 re_comment=re.compile('<!--[^>]*-->')#HTML annotation 
 re_stopwords=re.compile('\u3000')# Remove useless '\u3000' character 
 s=re_cdata.sub('',htmlstr)# To get rid of CDATA
 s=re_script.sub('',s) # To get rid of SCRIPT
 s=re_style.sub('',s)# To get rid of style
 s=re_br.sub('\n',s)# will br Convert to newline 
 s=re_h.sub('',s) # To get rid of HTML  The label 
 s=re_comment.sub('',s)# To get rid of HTML annotation 
 s=re_stopwords.sub('',s)
 # Remove excess blank lines 
 blank_line=re.compile('\n+')
 s=blank_line.sub('\n',s)
 s=replaceCharEntity(s)# Replace the entity 
 return s

## Replace the commonly used HTML Character entities .
# Use the normal character substitution HTML A special character entity in .
# You can add new entity characters to CHAR_ENTITIES In the , Deal with more HTML Character entities .
#@param htmlstr HTML string .
def replaceCharEntity(htmlstr):
 CHAR_ENTITIES={'nbsp':' ','160':' ',
    'lt':'<','60':'<',
    'gt':'>','62':'>',
    'amp':'&','38':'&',
    'quot':'"','34':'"',}

 re_charEntity=re.compile(r'&#?(?P<name>\w+);')
 sz=re_charEntity.search(htmlstr)
 while sz:
  entity=sz.group()#entity The full name, such as &gt;
  key=sz.group('name')# Get rid of &; after entity, Such as &gt; for gt
  try:
   htmlstr=re_charEntity.sub(CHAR_ENTITIES[key],htmlstr,1)
   sz=re_charEntity.search(htmlstr)
  except KeyError:
   # Empty string instead 
   htmlstr=re_charEntity.sub('',htmlstr,1)
   sz=re_charEntity.search(htmlstr)
 return htmlstr

Related articles: