本文實(shí)例講述了python處理html轉(zhuǎn)義字符的方法。分享給大家供大家參考,具體如下:
最近在用Python處理網(wǎng)頁數(shù)據(jù)時(shí),經(jīng)常遇到一些html轉(zhuǎn)義字符(也叫html字符實(shí)體),例如<> 等。字符實(shí)體一般是為了表示網(wǎng)頁中的預(yù)留字符,比如>用>表示,防止被瀏覽器認(rèn)為是標(biāo)簽,具體參考w3school的HTML 字符實(shí)體。雖然很有用,但是它們會極度影響對于網(wǎng)頁數(shù)據(jù)的解析。為了處理這些轉(zhuǎn)義字符,有如下解決方案:
1、使用HTMLParser處理
import HTMLParserhtml_cont = " asdfg>123<"html_parser = HTMLParser.HTMLParser()new_cont = html_parser.unescape(html_cont)print new_cont #new_cont = " asdfg>123<"
轉(zhuǎn)換回去(只是空格轉(zhuǎn)不回去了):
import cginew_cont = cgi.escape(new_cont)print new_cont #new_cont = " asdfg>123<"
2、直接挨個(gè)替換
html_cont = " asdfg>123<"new_cont = new_cont.replace(' ', ' ')print new_cont #new_cont = " asdfg>123<"new_cont = new_cont.replace('>', '>')print new_cont #new_cont = " asdfg>123<"new_cont = new_cont.replace('<', '<')print new_cont #new_cont = " asdfg>123<"不知道還有沒有更好的辦法。
另外stackoverflow上給出了在xml中處理轉(zhuǎn)義字符的解答:python - What's the best way to handle -like entities in XML documents with lxml? - Stack Overflow。
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python編碼操作技巧總結(jié)》、《Python圖片操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選