Windows Firefox" />

Python学习:获取标签属性

发布时间:2019-08-27 08:02:31编辑:auto阅读(1755)

    文件info.xml

    <?xml version="1.0" encoding="utf-8"?>
    <info>
     <base>
      <platform>Windows</platform>
      <browser>Firefox</browser>
      <url>http://www.baidu.com</url>
        <login username="admin" password="123456"/>
        <login username="guest" password="654321"/>
     </base>
     <test>
     <province>北京</province>
     <province>广东</province>
       <city>深圳</city>
       <city>珠海</city>
    <province>浙江</province>
       <city>杭州</city>
     </test>
    </info>
    1. 文件read_xml_1.py:获取任意标签名

    #coding=utf-8
    import xml.dom.minidom  
    dom =xml.dom.minidom.parse('E:\\Selenium_Relatived\\learning\\info.xml')
    
    root =dom.documentElement
    print(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-8
    import xml.dom.minidom  
    dom =xml.dom.minidom.parse('E:\\Selenium_Relatived\\learning\\info.xml')
    
    root =dom.documentElement
    print(root.nodeName)
    logins = root.getElementsByTagName('login')
    username=logins[0].getAttribute('username')
    print(username)
    username1=logins[1].getAttribute('username')
    print(username1)

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

    #coding=utf-8
    import xml.dom.minidom  
    dom =xml.dom.minidom.parse('E:\\Selenium_Relatived\\learning\\info.xml')
    
    root =dom.documentElement
    print(root.nodeName)
    province = dom.getElementsByTagName('province')
    citys = dom.getElementsByTagName('city')
    p2=province[1].firstChild.data
    print(p2)
    
    c1 = citys[0].firstChild.data
    
    print(c1)


关键字