Python学习:获取标签属性,,文件info.xml


文件info.xml

<?xmlversion="1.0"encoding="utf-8"?><info><base><platform>Windows</platform><browser>Firefox</browser><url>http://www.baidu.com</url><loginusername="admin"password="123456"/><loginusername="guest"password="654321"/></base><test><province>北京</province><province>广东</province><city>深圳</city><city>珠海</city><province>浙江</province><city>杭州</city></test></info>

文件read_xml_1.py:获取任意标签名

#coding=utf-8importxml.dom.minidomdom=xml.dom.minidom.parse(‘E:\\Selenium_Relatived\\learning\\info.xml‘)root=dom.documentElementprint(root.nodeName)tagname=root.getElementsByTagName(‘browser‘)print(tagname[0].tagName)tagname1=root.getElementsByTagName(‘login‘)print(tagname1[1].tagName)tagname2=root.getElementsByTagName(‘province‘)print(tagname2[2].tagName)

getElementsByTagName通过标签名获取标签,它所获得的对象是以数组形式存放


2.文件read_xml_2.py:获取标签的属性

#coding=utf-8importxml.dom.minidomdom=xml.dom.minidom.parse(‘E:\\Selenium_Relatived\\learning\\info.xml‘)root=dom.documentElementprint(root.nodeName)logins=root.getElementsByTagName(‘login‘)username=logins[0].getAttribute(‘username‘)print(username)username1=logins[1].getAttribute(‘username‘)print(username1)

3.获取标签对之间的数据

#coding=utf-8importxml.dom.minidomdom=xml.dom.minidom.parse(‘E:\\Selenium_Relatived\\learning\\info.xml‘)root=dom.documentElementprint(root.nodeName)province=dom.getElementsByTagName(‘province‘)citys=dom.getElementsByTagName(‘city‘)p2=province[1].firstChild.dataprint(p2)c1=citys[0].firstChild.dataprint(c1)


Python学习:获取标签属性

评论关闭