国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

編碼 - Python 3.6中 ’utf-8’ codec can’t decode byte invalid start byte?

瀏覽:145日期:2022-09-01 10:28:08

問題描述

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:

編碼 - Python 3.6中 ’utf-8’ codec can’t decode byte invalid start byte?

看了一下網站返回的是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)

編碼 - Python 3.6中 ’utf-8’ codec can’t decode byte invalid start byte?

回答2:

requests不好用嗎?

回答3:

編碼 - Python 3.6中 ’utf-8’ codec can’t decode byte invalid start byte?

建議用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 給解開

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 石楼县| 台江县| 文化| 余姚市| 重庆市| 武乡县| 秦皇岛市| 军事| 临安市| 南宁市| 阜新市| 邹平县| 关岭| 堆龙德庆县| 英吉沙县| 信阳市| 无极县| 河北省| 中方县| 瑞金市| 璧山县| 奉贤区| 玉环县| 九江市| 南投市| 汕尾市| 浦江县| 苍南县| 武冈市| 澄江县| 古浪县| 凤台县| 科尔| 武川县| 新竹县| 水富县| 宁津县| 弥渡县| 秭归县| 杭锦旗| 盐城市|