urllib查询返回的数据编码不正确

2024-04-28 19:35:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我从google图片中抓取了一些数据,发现像'î' 正在被错误地解码。在这种情况下'î'变成'î'。我在一个对象中存储了来自google查询的数据,其格式如下:

{"key":"value"}

但是,字典的值可以包含其他字符,例如:

{"key":"File:Blue tit (Cyanistes caeruleus), Parc du Rouge-Cloître, Brussels ( 32781868883).jpg"}

当我收到数据的时候

{"key":"File:Blue tit (Cyanistes caeruleus), Parc du Rouge-Clo\xc3\xaetre, Brussels ( 32781868883).jpg"}

因此,当我尝试将其转换为字节并使用以下方法解码时:

decoded_obj = bytes(raw_obj, 'utf-8').decode('unicode_escape')

我得到输出

{"key":"File:Blue tit (Cyanistes caeruleus), Parc du Rouge-Cloître, Brussels ( 32781868883).jpg"}

刮板代码如下:

import urllib.request
import json

url = 'https://www.google.com/search?q=Blue+tit+(Cyanistes+caeruleus),+Parc+du+Rouge-Clo%C3%AEtre,+Brussels+(32781868883).jpg&source=lnms&tbm=isch&sa=X&ved=0ahUKEwiE8866stfjAhWBolwKHQ1YCdQQ_AUIESgB&biw=1920&bih=937'

headers = {}
headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
request = urllib.request.Request(url, headers=headers)
response = urllib.request.urlopen(request)
data = str(response.read())

start_line = data.find('class="rg_meta notranslate">')
start_obj = data.find('{', start_line + 1)
end_obj = data.find('</div>', start_obj + 1)
raw_obj = str(data[start_obj:end_obj])

decoded_obj = bytes(raw_obj, 'utf-8').decode('unicode_escape')
final_obj = json.loads(decoded_obj)

print(final_obj)

Tags: keyobjdatarequestbluestartheadersjpg
1条回答
网友
1楼 · 发布于 2024-04-28 19:35:45

响应数据由UTF-8编码字节组成:

>>> response = urllib.request.urlopen(request)
>>> res = response.read()
>>> type(res)
<class 'bytes'>
>>> response.headers
<http.client.HTTPMessage object at 0x7ff6ea74ba90>
>>> response.headers['Content-type']                                                                                           
'text/html; charset=UTF-8'  

正确的处理方法是解码响应数据:

>>> data = response.read().decode('utf-8')

一旦这样做了,data就是一个str并且不需要任何进一步的解码或编码(或str()bytes()调用)

通常,在bytes实例上调用str是错误的,除非提供适当的编码:

>>> s = 'spam'
>>> bs = s.encode('utf-8')
>>> str(bs)
"b'spam'"   # Now 'b' is inside the string
>>> 

>>> str(bs, encoding='utf-8')
'spam'

相关问题 更多 >