我试图得到一个网页的内容和解析它比保存在mysql数据库。
我实际上是为一个编码为utf8的网页做的。
但是当我尝试使用8859-9编码网页时,我得到错误。
获取页面内容的代码:
def getcontent(url):
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Magic Browser')]
opener.addheaders = [('Accept-Charset', 'utf-8')]
#print chardet.detect(response).get('encoding)
response = opener.open(url).read()
opener.close()
return response
url = "http://www.meb.gov.tr/duyurular/index.asp?ID=4"
contentofpage = getcontent(url)
print contentofpage
print chardet.detect(contentofpage)
print contentofpage.encode("utf-8")
页面内容输出:…E - titim Teknolojileri Genel M - l - l…
{'confidence': 0.7789909202570836, 'encoding': 'ISO-8859-2'}
Traceback (most recent call last):
File "meb.py", line 18, in <module>
print contentofpage.encode("utf-8")
UnicodeDecodeError: 'ascii' codec can't decode byte 0xee in position 458: ordinal not in range(128)
实际上这个页面是土耳其语页面,编码是8859-9。
当我尝试使用默认编码时,我看到的都是"而不是一些字符。如何将页面内容转换为utf-8或土耳其语(iso-8859-9)
当我使用unicode (contentofpage)
it get
Traceback(最近一次调用):文件"meb.py",第20行打印unicode (contentofpage)UnicodeDecodeError: 'ascii'编解码器无法解码位置458的字节0xee:序数不在(128)范围内
我认为你想要解码,而不是编码,因为它已经编码了。
print contentofpage.decode("iso-8859-9")
产生如下示例:
Eğitim Teknolojileri Genel Müdürlüğü