requests模块
requests:
将python编译器当做浏览器使用,可以访问网站,并且接受返回的数据(字符串)
import requests
import json
# 发送http请求
response = requests.get("http://www.weather.com.cn/adat/sk/101010500.html")
response.encoding = 'utf-8'
result = response.text
print(type(result), result)
'''
<class 'str'> {"weatherinfo":{"city":"怀柔","cityid":"101010500","temp":"9","WD":"南风",
"WS":"1级","SD":"29%","WSE":"1","time":"10:25","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB",
"njd":"暂无实况","qy":"1007"}}
'''
dic = json.loads(result)
print(type(dic), dic)
'''
<class 'dict'> {'weatherinfo': {'city': '怀柔', 'cityid': '101010500', 'temp': '9', 'WD': '南风',
'WS': '1级', 'SD': '29%', 'WSE': '1', 'time': '10:25', 'isRadar': '1', 'Radar': 'JC_RADAR_AZ9010_JB',
'njd': '暂无实况', 'qy': '1007'}}
'''
1.检查QQ在线情况
import requests
# 使用第三方模块requests发送HTTP请求,或者XML格式内容
r = requests.get('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=123456789')
result = r.text #xml的字符串类型
from xml.etree import ElementTree as ET
# 解析XML格式内容
node = ET.XML(result) #XML接收一个字符串,格式化为特殊的对象
print(node)
# 获取内容
if node.text == "Y": #特殊的对象可以访问自己各个节点的信息
print("在线")
else:
print("离线")
2.火车站点详情
import requests
from xml.etree import ElementTree as ET
# 使用第三方模块requests发送HTTP请求,或者XML格式内容
r = requests.get(
'http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=')
result = r.text
# 解析XML格式内容,把字符串解析成XML
root = ET.XML(result)
print(root.tag)
for node in root:
print(node)
for node_node in node:
print(node_node)
for node_node_node in node_node:
print(node_node_node)