h3

php程序员学习python3学习第十二天

json的序列化,即其他数据结构转换为json,json转换为其他数据接口,进行数据交互

#-*- coding:utf-8 -*-
#json模块
import json
s1 = '{"name":"rcl","age":18}'
res1 = json.loads(s1) #json.loads() 将字符串形式的字典,列表,元组转换为对应的字典,列表,元组
print(res1)

s2 = '[11,22,33]'
res2 = json.loads(s2)
print(res2)

#将字典或者列表等转换成字符串
print(json.dumps(res2),type(json.dumps(res2))) #[11, 22, 33] <class 'str'>

#dump load  一般不用
#dump 将字典等转换成字符串,同时写入文件中, dumps 转换后的内容在内存中
# json.dump(res1, open('db', 'a'))
#load 先读文件中的内容,在将内容转换为对应的列表或者字典
res3 = json.load(open('db', 'r'))
print(res3, type(res3))

2,第三方模块的安装

# -*- coding: utf-8 -*-
#第三方模块使用的学习

'''
1,安装第三方模块
    软件管理工具pip3  python3 默认就有pip3,因此直接在环境变量中加上就可以使用了
        依赖setuptools
    源码安装 下载源码,安装
'''

import requests
安装方法

 3,requests模块初识

# -*- coding: utf-8 -*-
#初识requests

'''
response = requests.get('') 发起请求
response.text 获取返回内容
response.encoding = 'utf-8' 对结果进行编码
'''

import requests
response = requests.get('http://www.weather.com.cn/adat/sk/101050101.html')
response.encoding = 'utf-8'
print(response.text)
View Code

4,使用xml.etree进行解析xml格式的数据 from xml.etree import ElementTree as ET  检测qq在线

# -*- coding: utf-8 -*-
#检测qq是否在线
import requests
from xml.etree import ElementTree as ET

#使用第三方模块request 发请请求
r = requests.get('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=943716747')
res = r.text

#解析xml内容,接收xml字符串,格式化为特殊的对象
node = ET.XML(res)
flag = node.text
print(flag)
View Code

5,解析复杂结构的xml文件,获取其中的结果  使用for node in re.iter('xxxx'): 获取指定标签中的可迭代对象 node.find('xxx').text 获取其中指定标签的值

# -*- coding: utf-8 -*-
#检测列车时刻
import requests
from xml.etree import ElementTree as ET

r = requests.get('http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=K602&UserID=')
result = r.text

re = ET.XML(result)

for node in re.iter('TrainDetailInfo'): #取出其中的可迭代对象  去迭代的寻找其中的某一个节点,找其子孙
    # print(node.tag) #这个对象中标签
    print(node.find('TrainStation').text, node.find('StartTime').text) #获取此标签中对应标签的内容
View Code

 

posted @ 2017-06-05 21:08  码上平天下  阅读(75)  评论(0)    收藏  举报