python - 使用 HTMLParser 解析 unicode 时出错

标签 python unicode python-3.x

这是我为 Python 3.3 运行的代码:

from html.parser import HTMLParser

class TableParser(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.in_table = False
        self.in_table_header = False
        self.in_table_header_field = False
        self.table_fields = []

    def handle_starttag(self, tag, attributes):
        if tag == 'table':
            for name, value in attributes:
                if name == 'id' and value == 'data_table':
                    self.in_table = True
        if self.in_table == True:
            if tag == 'thead':
                self.in_table_header = True
        if self.in_table_header == True and tag == 'th':
            self.in_table_header_field = True

    def handle_endtag(self, tag):
        if tag == 'table':
            self.in_table = False
        if tag == 'thead':
            self.in_table_header = False
        if tag == 'th':
            self.in_table_header_field = False            

    def handle_data(self, data):
        if self.in_table_header_field == True:
            self.table_fields.append(data)

parser = TableParser()
parser.feed('<table id="data_table"><thead><tr><th>Company</th><th>Rapport</th><th>Price</th><th>Development 1&#229;r</th></thead></table>')
print(parser.table_fields)

这是输出:

['Company', 'Rapport', 'Price', 'Development 1', 'r']

我期待的是:

['Company', 'Rapport', 'Price', 'Development 1&#229;r']

或者更好:

['Company', 'Rapport', 'Price', 'Development 1år']

我做错了什么?

最佳答案

您需要为 HTMLParser.handle_charref() method 添加处理程序还有:

def handle_charref(self, name):
    self.handle_data(self.unescape('&#{};'.format(name)))

关于python - 使用 HTMLParser 解析 unicode 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18330273/

相关文章:

python - Devpi REST API - 如何检索包的版本

Python Sqlite3 : INSERT INTO table VALUE(dictionary goes here)

python - 结合负前瞻和后正则表达式

python - 遍历列表删除项目,一些项目没有被删除

C++ : Data retrieved from MySQL table in win32 applications

c++ - C++ exe (MSVC++2010) 中的 Unicode 问题

unicode - utf-32优势解释

Python 箭头添加小时/分钟/等 vs 替换

python - 在没有管理员访问权限的情况下使用 Python 获取 CPU 和 GPU 温度 - Windows

python - 除以零错误输入到Tkinter消息中供计算器使用