Discuss / Python / 作业

作业

Topic source

Champhy_Who

#1 Created at ... [Delete] [Delete and Lock User]
from urllib import request
import json
import ssl

def fetch_data(url):
    with request.urlopen(url,context=ssl._create_unverified_context()) as f:
        urldata=f.read()
        #将读取的url内容,内容为json,打开网站自己看
        #这里需要注意的是f.read()返回的是bytes,即未解码的
        #情况一:由于JSON可以被所有言语读取,所以无需解码
        #f.read().decode('utf-8')返回的是str,即unicod格式
        #情况二:一般针对的是其他标准的编码,gb2312等
        #一/二结果都是对的
        print(type(urldata))
    return json.loads(urldata)
        #反序列化,解析为python对象,这里也就是dict

如果有误,请指出


  • 1

Reply