1.示例如下:
    使用dom格式处理

    1. # -*- coding: utf-8 -*-
    2. import xml.dom.minidom #导入处理xml文件的模块
    3. import pandas as pd
    4. import csv
    5. #打开xml文档 并将这个文件对象存入dom变量
    6. dom = xml.dom.minidom.parse('242.xml')
    7. # documentElement用于得到dom对象的文档元素,并把获得的对象给root
    8. root = dom.documentElement
    9. # print(root.nodeName)
    10. # print(root.nodeValue)
    11. # print(root.nodeType)
    12. # print(root.ELEMENT_NODE)
    13. # 获取<target>标签
    14. targets = root.getElementsByTagName('target')
    15. # print(ress,len(ress))
    16. # 创建一个csv文件,存储需要出的数据
    17. with open('result.csv','a+',newline='',encoding='utf-8') as csvfile:
    18. writer = csv.writer(csvfile)
    19. writer.writerow(['IP','端口','协议','服务','状态'])
    20. # 循环处理target标签的内容
    21. for target in targets:
    22. # 获取他的IP标签,格式是list,获取值的方式:list[0].childNodes[0].data,
    23. ip = target.getElementsByTagName('ip')[0].childNodes[0].data
    24. info = target.getElementsByTagName('record_results')
    25. # print(info,len(info))
    26. print(ip)
    27. # 获取value的标签列表,并获取其中的数据
    28. for values in info:
    29. ports = values.getElementsByTagName('value')
    30. aa = []
    31. # 长度为4的是port的value。
    32. if len(ports) == 4:
    33. for port in ports:
    34. # 获取value的值
    35. v = port.childNodes[0].data
    36. aa.append(v)
    37. print(aa)
    38. with open('result.csv','a+',newline='',encoding='utf-8') as csvfile:
    39. writer = csv.writer(csvfile)
    40. # 写入到csv中
    41. writer.writerow([ip,aa[0],aa[1],aa[2],aa[3]])
    42. print('*******')
    43. # print(d[0].data)
    44. # print(ports)
    45. print('=========================================================')