三十一、python中urllib和requests包详解

A、urllib
import urllib
import urllib.request
import json

'''
1、loads,dumps
json.loads():将字符串转化成python的基础数据类型(字符换===》列表字典元祖,字典中必须是“”)
json.dumps():将python的python基本数据类型转化成字符串(列表,字典===》字符串)
'''
s='{"status":1000,"desc":"OK"}' #里面的值必须是双引号

result=json.loads(s) #将一个形似字典,列表,元祖的字符串转化成字典或者列表,元祖
print(result,type(result))

s1=json.dumps(result)
print (s1,type(s1))
----------------------------------------------------

  {'status': 1000, 'desc': 'OK'} <class 'dict'>
  {"status": 1000, "desc": "OK"} <class 'str'>

----------------------------------------------------

'''
2、dump,load
json.dump():
json.load()
'''
s2=urllib.request.Request("http://www.weather.com.cn/adat/sk/101050101.html")
r=urllib.request.urlopen(s2)
result=str(r.read(),encoding="utf8")
print (result,type(result))
res=json.loads(result)
print (res,type(res))
----------------------------------------------------

   {"weatherinfo":{"city":"哈尔滨","cityid":"101050101","temp":"5","WD":"南风","WS":"3级","SD":"31%","WSE":"3","time":"10:00","isRadar":"1","Radar":"JC_RADAR_AZ9451_JB","njd":"暂无实况","qy":"999"}} <class 'str'>
   {'weatherinfo': {'city': '哈尔滨', 'cityid': '101050101', 'temp': '5', 'WD': '南风', 'WS': '3级', 'SD': '31%', 'WSE': '3', 'time': '10:00', 'isRadar': '1', 'Radar': 'JC_RADAR_AZ9451_JB', 'njd': '暂无实况', 'qy': '999'}} <class 'dict'>

----------------------------------------------------
'''
3、requests:第三方包
'''
import requests

response=requests.get("http://www.weather.com.cn/adat/sk/101050101.html")
response.encoding="utf-8"
result=response.text
#result=response.content
print (result,type(result))
------------------------------------------------------------

   {"weatherinfo":{"city":"哈尔滨","cityid":"101050101","temp":"5","WD":"南风","WS":"3级","SD":"31%","WSE":"3","time":"10:00","isRadar":"1","Radar":"JC_RADAR_AZ9451_JB","njd":"暂无实况","qy":"999"}} <class 'str'>


------------------------------------------------------------
print("-------------------------------------------------------------------------------------")

转载于:https://www.cnblogs.com/chushujin/p/9431312.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值