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