Python requests模块解析XML


 

1.request初识

import requests
res = requests.get("http://www.baidu.com")
res.encoding='utf-8'
text = res.text
print(text)

 

2.检查QQ是否在线(api感觉不准)

import requests
from xml.etree import ElementTree
qq_str = input('please input the qq that you want check!:')
url_str ='http://www.webxml.com.cn//webservices//qqOnlineWebService.asmx//qqCheckOnline?qqCode=%s'%qq_str
text_str = requests.get(url_str)
text_str.encoding='utf-8'
#解析xml格式内容,将字符串转为特殊的对象
node = ElementTree.XML(text_str.text)
if node.text == 'Y':
    print('QQ:{} 在线'.format(qq_str))
else:
    print('QQ:{} 离线'.format(qq_str))

 3.火车列表信息

import requests
from xml.etree import ElementTree

traincode_str = input('please input the code of the train:')
url_str = 'http://ws.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=%s&UserID='%traincode_str
respose_str =  requests.get(url_str)
respose_str.encoding = 'utf-8'
root = ElementTree.XML(respose_str.text) #将字符串解析为XML
for node in root.iter("TrainDetailInfo"): #迭代寻找TrainDetailInfo标签
    # print(node.tag,node.attrib) #node的标签和属性
    station_str = node.find('TrainStation').text  #寻找node下的标签
    arrivetime_str = node.find('ArriveTime').text
    starttime_str = node.find('StartTime').text
    info_str = '车站:{station},到达时间:{arrivetime},出发时间:{starttime}'.format(**{'station':station_str,\
                    'arrivetime':arrivetime_str,'starttime':starttime_str})
    print(info_str)

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM