首页 > 代码库 > Learn_Day12 模块2:模块1内容补充、requests模块、xml模块

Learn_Day12 模块2:模块1内容补充、requests模块、xml模块

模块1内容补充:

  • vars()    python自动设置的全局变量
  • 在py文件开头用三引号注释,表示是对py文件本身的注释
  • __doc__    py文件本身的文件注释
  • __file__    文件路径
  • __package__    导入py文件(自定义模块)的位置(文件夹,目录),用“.”分割
  • __cached__    缓存,python2版本无此属性
  • __name__    默认 __main__:主文件执行主函数前用作判断
  • json.loads(形似对象)    用于将形似列表、字典的字符串转换成相应的列表、字典;形似对象内部的字符串必须用双引号
  • “ ”    双引号在任一编程语言中均表示字符串
  • [ ]     在python中表示列表,其他语言中表示数组
  • { }    任一语言中均表示字典
"""
njksdk,smacboasehfk,nw

"""

print(vars())
# {‘__file__‘: ‘/Users/macpro1/PycharmProjects/Learn_qzkf/qz_day12/qz_day12_1_模块1补充.py‘,
# ‘__doc__‘: None,
# ‘__cached__‘: None,
# ‘__loader__‘: <_frozen_importlib_external.SourceFileLoader object at 0x1005a5d68>,
# ‘__package__‘: None,
# ‘__builtins__‘: <module ‘builtins‘ (built-in)>,
# ‘__name__‘: ‘__main__‘,
# ‘__spec__‘: None}
print(__doc__)  # njksdk,smacboasehfk,nw

a = ‘("11","22","33","alex")‘
import json
a = json.loads(a)
print(a)
 

安装第三方模块

1、软件管理工具安装
    pip3 install 模块名
    终端直接运行,不需要进入python运行
2、源码安装
    下载源码并解压,找到setup.py所在的文件夹
    在终端运行    cd setup.py所在的文件夹的路径
                          python3 setup.py install

requests模块

用于发送http请求(用python模拟浏览器浏览网页)
Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。
Requests 中也有一个内置的 JSON 解码器,助你处理 JSON 数据
import requests

r = requests.get("http://www.weather.com.cn/adat/sk/101010500.html")  # 发送get请求
r.encoding = "utf-8"  # 对给返回值进行编码
a = r.text  # 拿到返回值
print(a)
"""
{"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"}
 }
"""

xml模块

http操作
技术分享
 1 import requests
 2 from xml.etree import ElementTree as ET  # 导入模块并重新命名为ET
 3 
 4 # 验证qq在线状态
 5 r = requests.get(
 6     http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=725367)  # 发送get请求
 7 a = r.text  # 拿到返回值
 8 
 9 n = ET.XML(a)  # 获得xml格式对象(将返回值XML格式化)
10 if n.text == "Y":  # 获取标签中间的内容
11     print("在线")
12 else:
13     print("离线")
# 验证QQ在线状态
技术分享
 1 import requests
 2 from xml.etree import ElementTree as ET  # 导入模块并重新命名为ET
 3 
 4 # 查看列车时刻表
 5 r = requests.get(
 6     http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=)
 7 r = r.text  # # 拿到返回值
 8 # print(r)
 9 # 解析XML格式内容
10 n = ET.XML(r)  # 获得xml格式对象(将返回值XML格式化)
11 for i in n.iter(TrainDetailInfo):
12     print(i.find(TrainStation).text, i.find(StartTime).text, i.tag, i.attrib)
13     # n.iter(‘TrainDetailInfo‘) 寻找节点:TrainDetailInfo = 标签名,寻找标签名叫 TrainDetailInfo 的节点
14     # i.attrib  获取标签属性:
15     # i.find(‘TrainStation‘)   寻找标签:
16     # i.find(‘TrainStation‘).text   获取标签的内容
17 
18 
19 """
20 西安北(车次:G666) 15: 58:00
21 TrainDetailInfo
22 {‘{urn:schemas-microsoft-com:xml-msdata}rowOrder‘: ‘0‘,
23  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}id‘: ‘TrainDetailInfo1‘,
24  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}hasChanges‘: ‘inserted‘}
25 渭南北
26 16: 17:00
27 TrainDetailInfo
28 {‘{urn:schemas-microsoft-com:xml-msdata}rowOrder‘: ‘1‘,
29  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}id‘: ‘TrainDetailInfo2‘,
30  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}hasChanges‘: ‘inserted‘}
31 三门峡南
32 17: 01:00
33 TrainDetailInfo
34 {‘{urn:schemas-microsoft-com:xml-msdata}rowOrder‘: ‘2‘,
35  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}id‘: ‘TrainDetailInfo3‘,
36  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}hasChanges‘: ‘inserted‘}
37 洛阳龙门
38 17: 34:00
39 TrainDetailInfo
40 {‘{urn:schemas-microsoft-com:xml-msdata}rowOrder‘: ‘3‘,
41  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}id‘: ‘TrainDetailInfo4‘,
42  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}hasChanges‘: ‘inserted‘}
43 郑州东
44 18: 20:00
45 TrainDetailInfo
46 {‘{urn:schemas-microsoft-com:xml-msdata}rowOrder‘: ‘4‘,
47  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}id‘: ‘TrainDetailInfo5‘,
48  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}hasChanges‘: ‘inserted‘}
49 安阳东
50 19: 03:00
51 TrainDetailInfo
52 {‘{urn:schemas-microsoft-com:xml-msdata}rowOrder‘: ‘5‘,
53  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}id‘: ‘TrainDetailInfo6‘,
54  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}hasChanges‘: ‘inserted‘}
55 邯郸东
56 19: 22:00
57 TrainDetailInfo
58 {‘{urn:schemas-microsoft-com:xml-msdata}rowOrder‘: ‘6‘,
59  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}id‘: ‘TrainDetailInfo7‘,
60  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}hasChanges‘: ‘inserted‘}
61 石家庄
62 20: 11:00
63 TrainDetailInfo
64 {‘{urn:schemas-microsoft-com:xml-msdata}rowOrder‘: ‘7‘,
65  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}id‘: ‘TrainDetailInfo8‘,
66  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}hasChanges‘: ‘inserted‘}
67 高碑店东
68 21: 01:00
69 TrainDetailInfo
70 {‘{urn:schemas-microsoft-com:xml-msdata}rowOrder‘: ‘8‘,
71  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}id‘: ‘TrainDetailInfo9‘,
72  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}hasChanges‘: ‘inserted‘}
73 北京西
74 None
75 TrainDetailInfo
76 {‘{urn:schemas-microsoft-com:xml-msdata}rowOrder‘: ‘9‘,
77  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}id‘: ‘TrainDetailInfo10‘,
78  ‘{urn:schemas-microsoft-com:xml-diffgram-v1}hasChanges‘: ‘inserted‘}
79 """
View Code
技术分享
1 print(n.tag)  # 获取根节点
2 # {http://WebXml.com.cn/}DataSet
# 获取根节点

文件操作

技术分享
 1 from xml.etree import ElementTree as ET  # 导入模块并重新命名为ET
 2 
 3 # 方法1
 4 f = open("first.xml", "r", encoding=utf-8)
 5 
 6 r = ET.XML(f.read())
 7 
 8 # iter与find都是寻找的意思,iter用于寻找节点的标签,find用于寻找节点内的标签。
 9 for n2 in r.find(country):
10     print(n2)
11     """
12     <Element ‘rank‘ at 0x102220138>
13     <Element ‘year‘ at 0x102220188>
14     <Element ‘gdppc‘ at 0x1022201d8>
15     <Element ‘neighbor‘ at 0x102220228>
16     <Element ‘neighbor‘ at 0x102220278>
17     """
18 for n2 in r.iter(country):
19     print(n2)
20     """
21     <Element ‘country‘ at 0x102223908>
22     <Element ‘country‘ at 0x1022202c8>
23     <Element ‘country‘ at 0x102220458>
24     """
25 
26 # 方法2
27 r = ET.parse("first.xml")
28 tree_first = r.getroot()  # 获取父节点
29 # 修改
30 for i in tree_first.iter("year"):
31     new_year = int(i.text) + 1
32     i.text = str(new_year)  # 对xml进行更改(必须是str才能保存)
33     i.set("name", "renhang")
34     i.set("age", "19")
35     del i.attrib["name"] # 删除属性,因为xml文件为字典,所以删除属性时用[]括号
36 # 删除
37 for i in tree_first.iter("country"):  # 循环父节点下的country子节点
38     rank = int(i.find("rank").text)  # 将rank节点的值转换为数字
39     if rank > 50:
40         tree_first.remove(i)  # 删除子节点
41 
42 r.write("first.xml")
43 # i.set(a, b) 为标签添加或修改属性(a、b必须是字符串,必须传递a、b两个参数)
# xml文件基本操作
技术分享
 1 from xml.etree import ElementTree as ET  # 导入模块并重新命名为ET
 2 # 创建xml文件
 3 # 创建根节点
 4 r = ET.Element("famliy")
 5 
 6 # 创建子节点
 7 s1 = ET.Element(son, {name: 儿1})
 8 s2 = ET.Element(son, {"name": 儿2})
 9 
10 g1 = ET.Element(grandson, {name: 儿11})
11 g2 = ET.Element(grandson, {name: 儿12})
12 # 将g1、g2两子节点分别添加到s1、s2两个子节点内,s1、s2为g1、g2的父节点
13 s1.append(g1)
14 s1.append(g2)
15 
16 # 把s1、s2两个子节点添加到根节点中,r为s1、s2的父节点
17 r.append(s1)
18 r.append(s1)
19 
20 tree = ET.ElementTree(r)
21 tree.write(new.xml, encoding=utf-8, short_empty_elements=False)
# 创建xml文件
 
 

Learn_Day12 模块2:模块1内容补充、requests模块、xml模块