Python:webpag的错误内容编码

2024-10-06 10:29:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取一个网页的内容并解析它,而不是保存在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")

页面内容输出: ... 伊蒂姆·特克诺罗吉列里基因公司 ... 在

^{pr2}$

实际上这个页面是一个土耳其语页面,编码是8859-9。在

当我尝试使用默认编码时,我看到的全部内容都不是字符。如何将页面内容转换为utf-8或土耳其语(iso-8859-9)

当我使用 unicode(第页内容)

它得到了

回溯(最近一次呼叫): “文件”meb.py公司“,第20行,英寸 打印unicode(第页内容) UnicodeDecodeError:“ascii”编解码器无法解码位置458处的字节0xee:序号不在范围内(128)

有什么帮助吗?在


Tags: url网页内容编码response页面openerutf
1条回答
网友
1楼 · 发布于 2024-10-06 10:29:02

我想你想解码,而不是编码,因为它已经被编码了。在

print contentofpage.decode("iso-8859-9")

产生的样本如下:

^{pr2}$

相关问题 更多 >