編碼 - 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. [python2]local variable referenced before assignment問題2. 求救一下,用新版的phpstudy,數據庫過段時間會消失是什么情況?3. javascript - js setTimeout在雙重for循環中如何使用?4. javascript - 我的站點貌似被別人克隆了, google 搜索特定文章,除了域名不一樣,其他的都一樣,如何解決?5. python - 如何判斷字符串為企業注冊名稱6. php - 微信開發驗證服務器有效性7. python中怎么對列表以區間進行統計?8. javascript - 求幫助 , ATOM不顯示界面!!!!9. html - 爬蟲時出現“DNS lookup failed”,打開網頁卻沒問題,這是什么情況?10. html - 移動端radio無法選中
