編碼 - Python 3.6中 ’utf-8’ codec can’t decode byte invalid start byte?
問題描述
Python 3.6中,網頁信息解析失敗,試了很多種編碼,查看網頁的編碼方式也是utf-8。錯誤信息:’utf-8’ codec can’t decode byte 0x8b in position 1: invalid start byte?還有就是第一個print終端里打印出來的unicode內容是[b’x1fx8bx08x00x...]這種格式的,之前也有過這種情況,一個print打2個變量,就是b’x, 如果分來2行打又變回了漢字。是因為什么原因呢?
# -*- coding: utf-8 -*-import json , sqlite3import urllib.requesturl = (’http://wthrcdn.etouch.cn/weather_mini?city=%E4%B8%8A%E6%B5%B7’)resp = urllib.request.urlopen(url)content = resp.read()print(content)print(type(content))print(content.decode(’utf-8’))
問題解答
回答1:看了一下網站返回的是gzip壓縮過的數據,所以要進行解碼
# coding=utf-8from io import BytesIOimport gzipimport urllib.requesturl = (’http://wthrcdn.etouch.cn/weather_mini?city=%E4%B8%8A%E6%B5%B7’)resp = urllib.request.urlopen(url)content = resp.read() # content是壓縮過的數據buff = BytesIO(content) # 把content轉為文件對象f = gzip.GzipFile(fileobj=buff)res = f.read().decode(’utf-8’)print(res)
requests不好用嗎?
回答3:建議用requeset,代碼如下:
import requestsr = requests.get(’http://wthrcdn.etouch.cn/weather_mini?city=%E4%B8%8A%E6%B5%B7’)print(r.text)回答4:
不是字符編碼問題, 你看看你請求的 Respont headers
Status Code: 200 OK Access-Control-Allow-Headers: * Access-Control-Allow-Methods: * Access-Control-Allow-Origin: * Cache-Control: must-revalidate, max-age=300 Connection: Keep-Alive Content-Encoding: gzip Content-Length: 443 Date: Fri, 10 Mar 2017 03:20:46 GMT Fw-Cache-Status: hit Fw-Via: HTTP MISS from 58.59.19.99, DISK HIT from 183.131.161.27 Server: Tengine/2.1.2
是gzip, 如果用標準庫的東西, 還需要把gzip 給解開
相關文章:
1. 在html文件的目錄下輸入代碼按回車后顯示這個,哪位大佬幫幫我 呀2. 老師您的微信號是多少?3. node.js - nodejs開發中常用的連接mysql的庫4. windows7 ping不通虛擬機VMware上的linux(ubuntu)的ip5. mysql - jdbc的問題6. python - 我在使用pip install -r requirements.txt下載時,為什么部分能下載,部分不能下載7. 視頻文件不能播放,怎么辦?8. mysql - 分庫分表、分區、讀寫分離 這些都是用在什么場景下 ,會帶來哪些效率或者其他方面的好處9. 網頁爬蟲 - python 爬取網站 并解析非json內容10. mysql - 如何減少使用或者不用LEFT JOIN查詢?
