Python 解析XML

Python 解析XMLhtml

<configuration>


    <conf>
        <name>URL_to_start</name>
        <value>http://baike.baidu.com/item/python</value>
    </conf>

    <!-- 總爬取數量 默認:-1 無限制 -->
    <conf>
        <name>count</name>
        <value>10</value>
    </conf>

    <!-- 總爬取時間(分鐘) 默認:-1 無限制-->
    <conf>
        <name>run_time</name>
        <value>-1</value>
    </conf>

    <!-- 線程數 默認:1 -->
    <conf>
        <name>Thread_count</name>
        <value>1</value>
    </conf>

    <!-- URL匹配規則 請使用正則表達式 -->
    <conf>
        <name>URL_re</name>
        <value>*</value>
    </conf>
</configuration>

解析node

import xml.dom.minidom


class ReadConf:
    def read(self):
        # 打開xml文檔
        dom = xml.dom.minidom.parse('conf.xml')

        # 獲得文檔元素對象
        root = dom.documentElement

        conf_nodes = root.getElementsByTagName('conf')
        conf_dict = {}

        for conf_node in conf_nodes:
            conf_dict[conf_node.getElementsByTagName('name')[0].firstChild.data] = \
                conf_node.getElementsByTagName('value')[
                    0].firstChild.data

        return conf_dict
相關文章
相關標籤/搜索