久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

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

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

問題描述

Python 3.6中,網(wǎng)頁信息解析失敗,試了很多種編碼,查看網(wǎng)頁的編碼方式也是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:

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

看了一下網(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)

編碼 - 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:

不是字符編碼問題, 你看看你請(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)庫的東西, 還需要把gzip 給解開

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 城市| 龙门县| 北海市| 华坪县| 侯马市| 潼关县| 同德县| 崇州市| 茂名市| 黎平县| 铅山县| 桦南县| 西宁市| 日喀则市| 确山县| 河间市| 鄄城县| 花莲县| 漳州市| 客服| 垦利县| 长治市| 瑞昌市| 罗甸县| 越西县| 迁安市| 法库县| 金湖县| 吉林市| 金溪县| 邵阳县| 宁乡县| 蓬溪县| 遂宁市| 克山县| 含山县| 临洮县| 双桥区| 万载县| 安康市| 邵阳市|