所有人。
请允许我问以下问题。
我使用Python2.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清理来解决字符的问题。
我应该如何更改此脚本?
有什么建议吗?
非常感谢。你知道吗
仅使用lxml
正在加载输出.html在浏览器中显示:
相关问题 更多 >
编程相关推荐