---
title: "用python将html去除格式转unicode"
author: "splayx"
date: "2013-07-17T17:43:50Z"
tags: []
categories: ["编程语言"]
slug: "python-html-unicode"
draft: false
lastmod: "2013-07-17T17:43:50Z"
id: 1908558
url: "https://splayx.iteye.com/blog/1908558"
---

见html中的一些奇怪的编码

http://www.w3school.com.cn/tags/html\_ref\_symbols.html

例如以下这么一串东西就是实体编码

&#23567;&#20309;&#24456;&#22909;&#21834;&#65281;

 

如果一个html文本想把它去除html的tag，然后又把它转为系统可识别的编码（例如utf8）

以下python代码把它转为unicode，然后想转什么都可以了。

 

```
from HTMLParser import HTMLParser

def strip_tags(html):
    html_parser = HTMLParser()

    # remove format
    #html = html.strip()
    #html = html.strip("\n")
    result=[]
    html_parser.handle_data = result.append
    html_parser.feed(html)

    # transform entity to unicode
    result = [html_parser.unescape(el) for el in result]

    html_parser.close()
    return "".join(result)
```