第三方requests模块

时间:2021-12-31 03:12:30

requests模块

requests:

     将python编译器当做浏览器使用,可以访问网站,并且接受返回的数据(字符串)

 

 1 import requests
2 import json
3
4 # 发送http请求
5 response = requests.get("http://www.weather.com.cn/adat/sk/101010500.html")
6 response.encoding = 'utf-8'
7 result = response.text
8 print(type(result), result)
9
10 # <class 'str'> {"weatherinfo":{"city":"怀柔","cityid":"101010500","temp":"9","WD":"南风",
11 # "WS":"1级","SD":"29%","WSE":"1","time":"10:25","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB",
12 # "njd":"暂无实况","qy":"1007"}}
13
14
15 dic = json.loads(result)
16 print(type(dic), dic)
17
18 # <class 'dict'> {'weatherinfo': {'city': '怀柔', 'cityid': '101010500', 'temp': '9', 'WD': '南风',
19 # 'WS': '1级', 'SD': '29%', 'WSE': '1', 'time': '10:25', 'isRadar': '1', 'Radar': 'JC_RADAR_AZ9010_JB',
20 # 'njd': '暂无实况', 'qy': '1007'}}

1.检查QQ在线情况

 1 import requests
2
3 # 使用第三方模块requests发送HTTP请求,或者XML格式内容
4 r = requests.get('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=123456789')
5 result = r.text #xml的字符串类型
6
7
8 from xml.etree import ElementTree as ET
9
10 # 解析XML格式内容
11 node = ET.XML(result) #XML接收一个字符串,格式化为特殊的对象
12 print(node)
13
14 # 获取内容
15 if node.text == "Y": #特殊的对象可以访问自己各个节点的信息
16 print("在线")
17 else:
18 print("离线")

2.火车站点详情

 1 import requests
2
3 from xml.etree import ElementTree as ET
4
5 # 使用第三方模块requests发送HTTP请求,或者XML格式内容
6 r = requests.get(
7 'http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=')
8 result = r.text
9
10 # 解析XML格式内容,把字符串解析成XML
11 root = ET.XML(result)
12
13 print(root.tag)
14 for node in root:
15 print(node)
16 for node_node in node:
17 print(node_node)
18 for node_node_node in node_node:
19 print(node_node_node)