99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python正則獲取、過濾或者替換HTML標簽的方法
Python正則獲取、過濾或者替換HTML標簽的方法
2017-09-19
收藏

Python正則獲取、過濾或者替換HTML標簽的方法

本文實例介紹了Python通過正則表達式獲取,去除(過濾)或者替換HTML標簽的幾種方法,具體內(nèi)容如下
python正則表達式關(guān)鍵內(nèi)容:
python正則表達式轉(zhuǎn)義符:    
. 匹配除換行符以外的任意字符
\w 匹配字母或數(shù)字或下劃線或漢字
\s 匹配任意的空白符
\d 匹配數(shù)字
\b 匹配單詞的開始或結(jié)束
^ 匹配字符串的開始
$ 匹配字符串的結(jié)束
\W 匹配任意不是字母,數(shù)字,下劃線,漢字的字符
\S 匹配任意不是空白符的字符
\D 匹配任意非數(shù)字的字符
\B 匹配不是單詞開頭或結(jié)束的位置
[^x] 匹配除了x以外的任意字符
[^aeiou] 匹配除了aeiou這幾個字母以外的任意字符

常用的python正則表達式限定符代碼/語法說明:
    
*重復(fù)零次或更多次
+重復(fù)一次或更多次
?重復(fù)零次或一次
{n}重復(fù)n次
{n,}重復(fù)n次或更多次
{n,m}重復(fù)n到m次

關(guān)于python正則表達式命名組:
    
命名組:(?P<name>.....)
這篇文章里面還提到了界定( 問號開頭,前向則有個'<'號,非則有個'!' 號 ):
前向界定 (?<=…)
后向界定 (?=…)
前向非界定 (?<!....)
后向非界定 (?!.....)

Python通過正則表達式獲取,去除(過濾)或者替換HTML標簽代碼舉例

1、Python通過正則表達式取html中天氣信息代碼示例:    
#!/usr/bin/env python
#-*- coding: utf8 -*-
import re
   
html = """
  <h2>多云</h2>
"""
   
if __name__ == '__main__':
  p = re.compile('<[^>]+>')
  print p.sub("", html)
Python通過正則表達式取html中溫度信息代碼示例:
#!/usr/bin/env python
#-*- coding: utf8 -*-
import re
   
html = """
  <div class="w-number"> <span class="tpte">14℃</span> </div>
"""
   
if __name__ == '__main__':
  p = re.compile('<[^>]+>')
  print p.sub("", html)

2、Python通過正則表達式去除(過濾)HTML標簽示例代碼:    
# -*- coding: utf-8-*-
import re
##過濾HTML中的標簽
#將HTML中標簽等信息去掉
#@param htmlstr HTML字符串.
def filter_tags(htmlstr):
  #先過濾CDATA
  re_cdata=re.compile('//<!\[CDATA\[[^>]*//\]\]>',re.I) #匹配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*?/?>')#處理換行
  re_h=re.compile('</?\w+[^>]*>')#HTML標簽
  re_comment=re.compile('<!--[^>]*-->')#HTML注釋
  s=re_cdata.sub('',htmlstr)#去掉CDATA
  s=re_script.sub('',s) #去掉SCRIPT
  s=re_style.sub('',s)#去掉style
  s=re_br.sub('\n',s)#將br轉(zhuǎn)換為換行
  s=re_h.sub('',s) #去掉HTML 標簽
  s=re_comment.sub('',s)#去掉HTML注釋
  #去掉多余的空行
  blank_line=re.compile('\n+')
  s=blank_line.sub('\n',s)
  s=replaceCharEntity(s)#替換實體
  return s
##替換常用HTML字符實體.
#使用正常的字符替換HTML中特殊的字符實體.
#你可以添加新的實體字符到CHAR_ENTITIES中,處理更多HTML字符實體.
#@param htmlstr HTML字符串.
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全稱,如>
    key=sz.group('name')#去除&;后entity,如>為gt
    try:
      htmlstr=re_charEntity.sub(CHAR_ENTITIES[key],htmlstr,1)
      sz=re_charEntity.search(htmlstr)
    except KeyError:
      #以空串代替
      htmlstr=re_charEntity.sub('',htmlstr,1)
      sz=re_charEntity.search(htmlstr)
  return htmlstr
def repalce(s,re_exp,repl_string):
  return re_exp.sub(repl_string,s)
if __name__=='__main__':
  s=file('169it.com_index.htm').read()
  news=filter_tags(s)
  print news
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助。

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }