標籤:
樣本:
#!/usr/bin/env python# -*- coding: utf-8 -*-import urllib import urllib2 def main():url = "http://www.douban.com"#瀏覽器頭headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}req = urllib2.Request(url=url,headers=headers)data = urllib2.urlopen(req).read()print datareturn 0 if __name__ == '__main__':main()
列印出來的內容中,漢字為亂碼。解決方案:
#!/usr/bin/env python# -*- coding: utf-8 -*-import urllib import urllib2import sys type = sys.getfilesystemencoding() def main():url = "http://www.douban.com"#瀏覽器頭headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}req = urllib2.Request(url=url,headers=headers)data = urllib2.urlopen(req).read()print data.decode("UTF-8").encode(type)return 0 if __name__ == '__main__':main()
有關python的encode和decode使用方法參見:http://blog.csdn.net/xyw_blog/article/details/40188037
本文為xyw_Eliot原創。轉載請註明出處:http://blog.csdn.net/xyw_blog/article/details/40187913
著作權聲明:本文部落格原創文章,部落格,未經同意,不得轉載。
python解決urllib2亂碼問題