Python错误:lxml + tidylib /我想解决grabled字符

时间:2014-02-11 16:40:52

标签: python unicode character-encoding lxml htmltidy

大家。
请让我提出以下问题。
我用python 2.6编写了这个脚本 但我得到了一个错误。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cchardet, urllib2
import lxml.html
from tidylib import tidy_document

class ParseHTML(object):
    def __init__(self, html):
        self.charset = cchardet.detect(html)['encoding']
        self.html = html
        self.html = self.html.decode(self.charset) # lineA
        self.document, self.errors = tidy_document(self.html)
        self.dom = lxml.html.fromstring(self.document)
    def getTitle(self):
        self.title = self.dom.xpath('//title')[0].text
        return self.title.strip()

url = r'http://www.asahi.com/articles/ASG2B5T0ZG2BUHBI131.html?iref=comtop_6_01'
response = urllib2.urlopen(url)
html = response.read()
parse = ParseHTML(html)
title = parse.getTitle()
print title

然后我有一个错误。

ValueError: Unicode strings with encoding declaration are not supported.

如果我注释掉lineA,脚本会起作用,但结果会变得乱码 我被乱码所困扰 我想通过HTML Tidy来解决字符问题。

我该如何更改此脚本?
有什么建议吗? 谢谢。

1 个答案:

答案 0 :(得分:0)

这仅使用lxml

>>> from lxml import etree
>>> with open('out.html', 'w') as f:
...     root = etree.parse(url, etree.HTMLParser())
...     title = root.xpath('//title/text()')[0]
...     f.write(title.encode("utf-8"))

在浏览器中加载out.html显示:

中国・台湾、窓口役の担当閣僚が会談 49年の分断後初:朝日新聞デジタル