在python中检测和更改网站编码

2024-09-27 00:18:53 发布

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

我对网站编码有问题。我做了一个程序来抓取一个网站,但我没有成功地改变阅读内容的编码。我的代码是:

import sys,os,glob,re,datetime,optparse
import urllib2

from BSXPath import BSXPathEvaluator,XPathResult
#import BeautifulSoup

#from utility import *

sTargetEncoding = "utf-8"

page_to_process = "http://www.xxxx.com" 
req = urllib2.urlopen(page_to_process)
content = req.read()
encoding=req.headers['content-type'].split('charset=')[-1]
print encoding

ucontent = unicode(content, encoding).encode(sTargetEncoding)
#ucontent = content.decode(encoding).encode(sTargetEncoding)
#ucontent = content

document = BSXPathEvaluator(ucontent)

print "ORIGINAL ENCODING: " + document.originalEncoding

我使用了外部库(BSXPath是BeautifulSoap的扩展)和文档.原始编码打印网站的编码,而不是我试图更改的utf-8编码。 有什么建议吗?在

谢谢


Tags: tofromimport编码网站pagecontenturllib2
1条回答
网友
1楼 · 发布于 2024-09-27 00:18:53

好吧,不能保证HTTP报头呈现的编码与HTML本身中指定的编码相同。这可能是由于服务器端的配置错误,或者HTML中的字符集定义可能是错误的。实际上没有自动的方法来检测编码或检测编码。你可以很容易地检测到你的应用程序内部的编码和硬编码。在

相关问题 更多 >

    热门问题