Python错误:lxml+;tidylib/I';我想解决抓取字符
所有人。Python错误:lxml+;tidylib/I';我想解决抓取字符,python,unicode,character-encoding,lxml,htmltidy,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 = cc
请让我问一个问题。
我使用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.
那我就错了。#!/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解决字符净化问题。
如何更改此脚本?
有什么建议吗?
谢谢。这只使用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年の分断後初:朝日新聞デジタル
嗨,盖伊·加弗里利。谢谢你的回答。多亏了你的回答,我才发现问题所在。非常感谢。很高兴能帮助你:请考虑把答案标记为正确。