編碼 - Python 3.6中 ’utf-8’ codec can’t decode byte invalid start byte?
問題描述
Python 3.6中,網(wǎng)頁(yè)信息解析失敗,試了很多種編碼,查看網(wǎng)頁(yè)的編碼方式也是utf-8。錯(cuò)誤信息:’utf-8’ codec can’t decode byte 0x8b in position 1: invalid start byte?還有就是第一個(gè)print終端里打印出來的unicode內(nèi)容是[b’x1fx8bx08x00x...]這種格式的,之前也有過這種情況,一個(gè)print打2個(gè)變量,就是b’x, 如果分來2行打又變回了漢字。是因?yàn)槭裁丛蚰兀?/p>
# -*- 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:看了一下網(wǎng)站返回的是gzip壓縮過的數(shù)據(jù),所以要進(jìn)行解碼
# 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是壓縮過的數(shù)據(jù)buff = BytesIO(content) # 把content轉(zhuǎn)為文件對(duì)象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:
不是字符編碼問題, 你看看你請(qǐng)求的 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, 如果用標(biāo)準(zhǔn)庫(kù)的東西, 還需要把gzip 給解開
相關(guān)文章:
1. 求大神支招,php怎么操作在一個(gè)html文件的<head>標(biāo)記內(nèi)添加內(nèi)容?2. 安裝了“PHP工具箱”,但只能以“游客”身份登錄3. 老師們php,插入數(shù)據(jù)庫(kù)mysql,都是空的,要怎么解決4. 跨類調(diào)用后,找不到方法5. 在mybatis使用mysql的ON DUPLICATE KEY UPDATE語法實(shí)現(xiàn)存在即更新應(yīng)該使用哪個(gè)標(biāo)簽?6. 致命錯(cuò)誤: Class ’appfacadeTest’ not found7. 在應(yīng)用配置文件 app.php 中找不到’route_check_cache’配置項(xiàng)8. PHP類屬性聲明?9. 怎么php怎么通過數(shù)組顯示sql查詢結(jié)果呢,查詢結(jié)果有多條,如圖。10. phpstady在win10上運(yùn)行
