1. 參考
HTML 字符實體
比方說一個從網頁中抓到的字符串
html = '<abc>'
用Python可以這樣處理:
import HTMLParser html_parser = HTMLParser.HTMLParser() txt = html_parser.unescape(html) #這樣就得到了txt = '<abc>'
如果還想轉回去,可以這樣:
import cgi html = cgi.escape(txt) # 這樣又回到了 html = '<abc>'
2. 常用
顯示結果 | 描述 | 實體名稱 | 實體編號 |
---|---|---|---|
空格 | |   | |
< | 小於號 | < | < |
> | 大於號 | > | > |
& | 和號 | & | & |
" | 引號 | " | " |
' | 撇號 | ' (IE不支持) | ' |
3. 代碼
1 In [354]: soup = BeautifulSoup("“Dammit!” he said.") 2 3 In [355]: unicode(soup) 4 Out[355]: u'<html><body><p>\u201cDammit!\u201d he said.</p></body></html>' 5 6 In [358]: str(soup) 7 Out[358]: '<html><body><p>\xe2\x80\x9cDammit!\xe2\x80\x9d he said.</p></body></html>' 8 9 In [359]: print str(soup).decode('utf-8') 10 <html><body><p>“Dammit!” he said.</p></body></html> 11 12 In [360]: print unicode(soup) 13 <html><body><p>“Dammit!” he said.</p></body></html>