Python_模块

本节大纲:

  1.模块介绍

  2.time&datetime模块

  3.random

  4.os

  5.sys

  6.json&picle

  7.hashlib

  8.XML

  9.requests

  10.configparser

  11.logging

 

模块介绍

  Python Module(模块),就是一个保存了Python代码的文件。模块能定义函数,类和变量。模块里也能包含可执行的代码。

  文件名就是模块名加上后缀.py,在模块内部,模块名存储在全局变量__name__中,是一个string,可以直接在module中通过__name__应用到module name

模块分为三种:

  · 自定义模块

  · 内置标准模块(又称标准库)

  · 开源模块

 

导入模块:

  · import:使客户端(导入者)以一个整体获取一个模块

  · from:容许客户端从一个模块文件中获取特定的变量名

  · reload:在不终止Python程序的情况下,提供了一个重新载入模块文件代码的方法

1 import module
2 from module.xx.xx import xx
3 from module.xx.xx import xx as rename 
4 from module.xx.xx import *

模块路径:

 1 #获取路径
 2 import sys
 3 for i in sys.path:
 4     print(i)
 5 #输出结果:
 6 S:\Myproject
 7 S:\Python 3.5.1\python35.zip
 8 S:\Python 3.5.1\DLLs
 9 S:\Python 3.5.1\lib                  #存放标准库
10 S:\Python 3.5.1
11 S:\Python 3.5.1\lib\site-packages    #存放第三方库,扩充库
12  
13 #添加路径
14 import sys
15 import os
16 pre_path = os.path.abspath('../')
17 sys.path.append(pre_path)

开源模块:

自定义模块和开源模块的使用参http://www.cnblogs.com/wupeiqi/articles/4963027.html

#time&datetime模块

时间相关的操作,时间有三种表示方式:

  · 时间戳        1970年1月1日之后的秒,即:time.time()

  · 格式化的字符串       2014-11-11 11:11,即time.strftime('%Y-%m-%d)

  · 结构化时间          元组包含了:年、日、星期等...time.struct_time,即time.localtime()

 1 import time
 2 print(time.time())                  #返回当前系统时间戳(1970年1月1日0时0分0秒开始)
 3 print(time.ctime())                 #输出Tue May 17 16:07:11 2016,当前系统时间
 4 print(time.ctime(time.time() - 86400))        #将时间戳转换为字符串格式
 5 print(time.gmtime(time.time() - 86400))      #将时间戳转换为struct_time格式
 6 print(time.localtime(time.time() - 86400))     #将时间戳转换为struct_time格式,返回本地时间
 7 print(time.mktime(time.localtime()))         #与time.localtime()功能相反,将struct_time格式转回成时间戳格式
 8 #time.sleep(5)                    #sleep停顿
 9 print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()))  #将struct_time格式转成指定的字符串格式
10 print(time.strptime("2016-05-17","%Y-%m-%d"))   #将字符串格式转换成struct_time格式
11  
12  
13 print("----------------------------------------------------------------")
14 import datetime
15 print(datetime.date.today())             #输出格式 2016-05-17
16 print(datetime.date.fromtimestamp(time.time() - 86400)) #2016-05-16 将时间戳转成日期格式
17 current_time = datetime.datetime.now()
18 print(current_time)                 #输出2016-05-17 16:18:28.737561
19 print(current_time.timetuple())          #返回struct_time格式
20 print(current_time.replace(2008,8,8))         #输出2008-08-08 16:21:34.798203,返回当前时间,但指定的值将被替换
21  
22 str_to_date = datetime.datetime.strptime("28/7/08 11:20","%d/%m/%y %H:%M")  #将字符串转换成日期格式
23 new_date = datetime.datetime.now() + datetime.timedelta(days=10)         #比现在加10天
24 new_date = datetime.datetime.now() + datetime.timedelta(days=-10)       #比现在减10天
25 new_date = datetime.datetime.now() + datetime.timedelta(hours=-10)       #比现在减10小时
26 new_date = datetime.datetime.now() + datetime.timedelta(seconds=120)      #比现在+120s
27 print(new_date)

random模块

随机数:

 1 import random
 2  
 3 print(random.random())          #用于生成一个0到1的随机符点数: 0 <= n < 1.0
 4 print(random.randint(1,2))      #用于生成一个指定范围内的整数
 5 print(random.randrange(1,10))   #从指定范围内,按指定基数递增的集合中获取一个随机数
 6 print(random.uniform(1,10))     #用于生成一个指定范围内的随机符点数
 7 print(random.choice('nick'))    #从序列中获取一个随机元素
 8 li = ['nick','jenny','car',]
 9 random.shuffle(li)              #用于将一个列表中的元素打乱
10 print(li)
11 li_new = random.sample(li,2)    #从指定序列中随机获取指定长度的片断(从li中随机获取2个元素,作为一个片断返回)
12 print(li_new)

生成随机验证码:

 1 ########## 随机验证码 ############
 2 import random
 3 temp = ''
 4 for i in range(4):
 5     num = random.randrange(0,4)
 6     if num == 0 or num == 3:        #一半的概率
 7         rad2 = random.randrange(0,10)
 8         temp = temp + str(rad2)
 9     else:
10         rad1 = random.randrange(65,91)
11         c1 = chr(rad1)
12         temp = temp + c1
13 print(temp)

OS模块

os模块用于提供系统级别的操作

 1 os.getcwd()                 获取当前工作目录,即当前python脚本工作的目录路径
 2 os.chdir("dirname")         改变当前脚本工作目录;相当于shell下cd
 3 os.curdir                   返回当前目录: ('.')
 4 os.pardir                   获取当前目录的父目录字符串名:('..')
 5 os.makedirs('dir1/dir2')    可生成多层递归目录
 6 os.removedirs('dirname1')   若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
 7 os.mkdir('dirname')         生成单级目录;相当于shell中mkdir dirname
 8 os.rmdir('dirname')         删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
 9 os.listdir('dirname')       列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
10 os.remove()                 删除一个文件
11 os.rename("oldname","new")  重命名文件/目录
12 os.stat('path/filename')    获取文件/目录信息
13 os.sep                      操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
14 os.linesep                  当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
15 os.pathsep                  用于分割文件路径的字符串
16 os.name                     字符串指示当前使用平台。win->'nt'; Linux->'posix'
17 os.system("bash command")   运行shell命令,直接显示
18 os.environ                  获取系统环境变量
19 os.path.abspath(path)       返回path规范化的绝对路径
20 os.path.split(path)         将path分割成目录和文件名二元组返回
21 os.path.dirname(path)       返回path的目录。其实就是os.path.split(path)的第一个元素
22 os.path.basename(path)      返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
23 os.path.exists(path)        如果path存在,返回True;如果path不存在,返回False
24 os.path.isabs(path)         如果path是绝对路径,返回True
25 os.path.isfile(path)        如果path是一个存在的文件,返回True。否则返回False
26 os.path.isdir(path)         如果path是一个存在的目录,则返回True。否则返回False
27 os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
28 os.path.getatime(path)      返回path所指向的文件或者目录的最后存取时间
29 os.path.getmtime(path)      返回path所指向的文件或者目录的最后修改时间

sys模块

用于提供对解释器相关的操作

1 sys.argv           命令行参数List,第一个元素是程序本身路径
2 sys.exit(n)        退出程序,正常退出时exit(0)
3 sys.version        获取Python解释程序的版本信息
4 sys.maxint         最大的Int值
5 sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
6 sys.platform       返回操作系统平台名称
7 sys.stdin          输入相关
8 sys.stdout         输出相关
9 sys.stderror       错误相关

Json&Picle模块

用于序列化的两个模块

  · json,用于字符串和Python数据类型间进行转换

  · pickle,用于Python特有的类型和Python的数据类型间进行转换

Json模块提供了四个功能:dumps、dump、loads、load

pickle模块提供了四个功能:dumps、dump、loads、load

  dump()函数接受一个文件句柄和一个数据对象作为参数,把数据对象以特定的格式保存到给定的文件中。当我们使用load()函数从文件中取出已保存的对象时,pickle知道如何恢复这些对象到它们本来的格式。

  dumps()函数执行和dump()函数相同的序列化。取代接受流对象并将序列化后的数据保存到磁盘文件,这个函数简单的返回序列化的数据。

  loads()函数执行和load()函数一样的反序列化。取代接受一个流对象病区文件读取序列化后的数据,它接受包含序列化后的数据的str对象,直接返回的对象。

 1 ##### json.loads 将字符串转换为python基本数据类型 列表字典 #####
 2 import json
 3 l = '["nick","jenny","car"]'
 4 print(l,type(l))
 5 l = json.loads(l)
 6 print(l,type(l))
 7  
 8 l = '{"k1":"nick","k2:":"jenny"}'
 9 print(l,type(l))
10 l = json.loads(l)
11 print(l,type(l))
12  
13 ##### json.dumps 将python的数据类型列表字典转换为字符串 ######
14 import json
15 l = ["nick","jenny","car"]
16 print(l,type(l))
17 l = json.dumps(l)
18 print(l,type(l))
19  
20 l = {"k1":"nick","k2:":"jenny"}
21 print(l,type(l))
22 l = json.dumps(l)
23 print(l,type(l))
24  
25 ##### json dump、load 文件相关 #####
26 import json
27 l = {"k1":"nick","k2:":"jenny"}
28 json.dump(l,open('db','w'))
29  
30 ret = json.load(open('db'))
31 print(ret)
32  

hashlib模块

用于加密相关的操作,代替了md5模块和sha模块,主要提供md5(),sha1(),sha224(),sha256(),sha384()和sha512()算法

import hashlib
 
# ######## md5 ########
hash = hashlib.md5()
# help(hash.update)
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
print(hash.digest())
 
 
######## sha1 ########
 
hash = hashlib.sha1()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
 
# ######## sha256 ########
 
hash = hashlib.sha256()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
 
 
# ######## sha384 ########
 
hash = hashlib.sha384()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
 
# ######## sha512 ########
 
hash = hashlib.sha512()
hash.update(bytes('admin', encoding='utf-8'))
print(hash.hexdigest())
 
 
##### 加盐 ######
# ######## md5 ########
 
hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8"))
hash.update(bytes('admin',encoding="utf-8"))
print(hash.hexdigest())
 
#python内置还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密
 
import hmac
 
h = hmac.new(bytes('898oaFs09f',encoding="utf-8"))
h.update(bytes('admin',encoding="utf-8"))
print(h.hexdigest())

XML模块

xml是实现不同语言或程序之间进行数据交换的协议,xml文件格式如下:

<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2023</year>
        <gdppc>141100</gdppc>
        <neighbor direction="E" name="Austria" />
        <neighbor direction="W" name="Switzerland" />
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2026</year>
        <gdppc>59900</gdppc>
        <neighbor direction="N" name="Malaysia" />
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2026</year>
        <gdppc>13600</gdppc>
        <neighbor direction="W" name="Costa Rica" />
        <neighbor direction="E" name="Colombia" />
    </country>
</data>

1.解析xml

from xml.etree import ElementTree as ET

# 打开文件,读取XML内容
str_xml = open('xo.xml', 'r').read()

# 将字符串解析成xml特殊对象,root代指xml文件的根节点
root = ET.XML(str_xml)

利用ElementTree.XML将字符串解析成xml对象
利用ElementTree.XML将字符串解析成xml对象
from xml.etree import ElementTree as ET

# 直接解析xml文件
tree = ET.parse("xo.xml")

# 获取xml文件的根节点
root = tree.getroot()

利用ElementTree.parse将文件直接解析成xml对象
利用ElementTree.parse将文件直接解析成xml对象

2.操作xml

xml格式类型是节点嵌套节点,对于每一个节点均有以下功能,以便对当前节点进行操作:

class Element:
    """An XML element.

    This class is the reference implementation of the Element interface.

    An element's length is its number of subelements.  That means if you
    want to check if an element is truly empty, you should check BOTH
    its length AND its text attribute.

    The element tag, attribute names, and attribute values can be either
    bytes or strings.

    *tag* is the element name.  *attrib* is an optional dictionary containing
    element attributes. *extra* are additional element attributes given as
    keyword arguments.

    Example form:
        <tag attrib>text<child/>...</tag>tail

    """

    当前节点的标签名
    tag = None
    """The element's name."""

    当前节点的属性

    attrib = None
    """Dictionary of the element's attributes."""

    当前节点的内容
    text = None
    """
    Text before first subelement. This is either a string or the value None.
    Note that if there is no text, this attribute may be either
    None or the empty string, depending on the parser.

    """

    tail = None
    """
    Text after this element's end tag, but before the next sibling element's
    start tag.  This is either a string or the value None.  Note that if there
    was no text, this attribute may be either None or an empty string,
    depending on the parser.

    """

    def __init__(self, tag, attrib={}, **extra):
        if not isinstance(attrib, dict):
            raise TypeError("attrib must be dict, not %s" % (
                attrib.__class__.__name__,))
        attrib = attrib.copy()
        attrib.update(extra)
        self.tag = tag
        self.attrib = attrib
        self._children = []

    def __repr__(self):
        return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self))

    def makeelement(self, tag, attrib):
        创建一个新节点
        """Create a new element with the same type.

        *tag* is a string containing the element name.
        *attrib* is a dictionary containing the element attributes.

        Do not call this method, use the SubElement factory function instead.

        """
        return self.__class__(tag, attrib)

    def copy(self):
        """Return copy of current element.

        This creates a shallow copy. Subelements will be shared with the
        original tree.

        """
        elem = self.makeelement(self.tag, self.attrib)
        elem.text = self.text
        elem.tail = self.tail
        elem[:] = self
        return elem

    def __len__(self):
        return len(self._children)

    def __bool__(self):
        warnings.warn(
            "The behavior of this method will change in future versions.  "
            "Use specific 'len(elem)' or 'elem is not None' test instead.",
            FutureWarning, stacklevel=2
            )
        return len(self._children) != 0 # emulate old behaviour, for now

    def __getitem__(self, index):
        return self._children[index]

    def __setitem__(self, index, element):
        # if isinstance(index, slice):
        #     for elt in element:
        #         assert iselement(elt)
        # else:
        #     assert iselement(element)
        self._children[index] = element

    def __delitem__(self, index):
        del self._children[index]

    def append(self, subelement):
        为当前节点追加一个子节点
        """Add *subelement* to the end of this element.

        The new element will appear in document order after the last existing
        subelement (or directly after the text, if it's the first subelement),
        but before the end tag for this element.

        """
        self._assert_is_element(subelement)
        self._children.append(subelement)

    def extend(self, elements):
        为当前节点扩展 n 个子节点
        """Append subelements from a sequence.

        *elements* is a sequence with zero or more elements.

        """
        for element in elements:
            self._assert_is_element(element)
        self._children.extend(elements)

    def insert(self, index, subelement):
        在当前节点的子节点中插入某个节点,即:为当前节点创建子节点,然后插入指定位置
        """Insert *subelement* at position *index*."""
        self._assert_is_element(subelement)
        self._children.insert(index, subelement)

    def _assert_is_element(self, e):
        # Need to refer to the actual Python implementation, not the
        # shadowing C implementation.
        if not isinstance(e, _Element_Py):
            raise TypeError('expected an Element, not %s' % type(e).__name__)

    def remove(self, subelement):
        在当前节点在子节点中删除某个节点
        """Remove matching subelement.

        Unlike the find methods, this method compares elements based on
        identity, NOT ON tag value or contents.  To remove subelements by
        other means, the easiest way is to use a list comprehension to
        select what elements to keep, and then use slice assignment to update
        the parent element.

        ValueError is raised if a matching element could not be found.

        """
        # assert iselement(element)
        self._children.remove(subelement)

    def getchildren(self):
        获取所有的子节点(废弃)
        """(Deprecated) Return all subelements.

        Elements are returned in document order.

        """
        warnings.warn(
            "This method will be removed in future versions.  "
            "Use 'list(elem)' or iteration over elem instead.",
            DeprecationWarning, stacklevel=2
            )
        return self._children

    def find(self, path, namespaces=None):
        获取第一个寻找到的子节点
        """Find first matching element by tag name or path.

        *path* is a string having either an element tag or an XPath,
        *namespaces* is an optional mapping from namespace prefix to full name.

        Return the first matching element, or None if no element was found.

        """
        return ElementPath.find(self, path, namespaces)

    def findtext(self, path, default=None, namespaces=None):
        获取第一个寻找到的子节点的内容
        """Find text for first matching element by tag name or path.

        *path* is a string having either an element tag or an XPath,
        *default* is the value to return if the element was not found,
        *namespaces* is an optional mapping from namespace prefix to full name.

        Return text content of first matching element, or default value if
        none was found.  Note that if an element is found having no text
        content, the empty string is returned.

        """
        return ElementPath.findtext(self, path, default, namespaces)

    def findall(self, path, namespaces=None):
        获取所有的子节点
        """Find all matching subelements by tag name or path.

        *path* is a string having either an element tag or an XPath,
        *namespaces* is an optional mapping from namespace prefix to full name.

        Returns list containing all matching elements in document order.

        """
        return ElementPath.findall(self, path, namespaces)

    def iterfind(self, path, namespaces=None):
        获取所有指定的节点,并创建一个迭代器(可以被for循环)
        """Find all matching subelements by tag name or path.

        *path* is a string having either an element tag or an XPath,
        *namespaces* is an optional mapping from namespace prefix to full name.

        Return an iterable yielding all matching elements in document order.

        """
        return ElementPath.iterfind(self, path, namespaces)

    def clear(self):
        清空节点
        """Reset element.

        This function removes all subelements, clears all attributes, and sets
        the text and tail attributes to None.

        """
        self.attrib.clear()
        self._children = []
        self.text = self.tail = None

    def get(self, key, default=None):
        获取当前节点的属性值
        """Get element attribute.

        Equivalent to attrib.get, but some implementations may handle this a
        bit more efficiently.  *key* is what attribute to look for, and
        *default* is what to return if the attribute was not found.

        Returns a string containing the attribute value, or the default if
        attribute was not found.

        """
        return self.attrib.get(key, default)

    def set(self, key, value):
        为当前节点设置属性值
        """Set element attribute.

        Equivalent to attrib[key] = value, but some implementations may handle
        this a bit more efficiently.  *key* is what attribute to set, and
        *value* is the attribute value to set it to.

        """
        self.attrib[key] = value

    def keys(self):
        获取当前节点的所有属性的 key

        """Get list of attribute names.

        Names are returned in an arbitrary order, just like an ordinary
        Python dict.  Equivalent to attrib.keys()

        """
        return self.attrib.keys()

    def items(self):
        获取当前节点的所有属性值,每个属性都是一个键值对
        """Get element attributes as a sequence.

        The attributes are returned in arbitrary order.  Equivalent to
        attrib.items().

        Return a list of (name, value) tuples.

        """
        return self.attrib.items()

    def iter(self, tag=None):
        在当前节点的子孙中根据节点名称寻找所有指定的节点,并返回一个迭代器(可以被for循环)。
        """Create tree iterator.

        The iterator loops over the element and all subelements in document
        order, returning all elements with a matching tag.

        If the tree structure is modified during iteration, new or removed
        elements may or may not be included.  To get a stable set, use the
        list() function on the iterator, and loop over the resulting list.

        *tag* is what tags to look for (default is to return all elements)

        Return an iterator containing all the matching elements.

        """
        if tag == "*":
            tag = None
        if tag is None or self.tag == tag:
            yield self
        for e in self._children:
            yield from e.iter(tag)

    # compatibility
    def getiterator(self, tag=None):
        # Change for a DeprecationWarning in 1.4
        warnings.warn(
            "This method will be removed in future versions.  "
            "Use 'elem.iter()' or 'list(elem.iter())' instead.",
            PendingDeprecationWarning, stacklevel=2
        )
        return list(self.iter(tag))

    def itertext(self):
        在当前节点的子孙中根据节点名称寻找所有指定的节点的内容,并返回一个迭代器(可以被for循环)。
        """Create text iterator.

        The iterator loops over the element and all subelements in document
        order, returning all inner text.

        """
        tag = self.tag
        if not isinstance(tag, str) and tag is not None:
            return
        if self.text:
            yield self.text
        for e in self:
            yield from e.itertext()
            if e.tail:
                yield e.tail

源码
xml官方源码

由于每个节点都具有以上的方法,并且在上一步骤中解析时均得到了root(xml文件的根节点),所以可以利用以上方法进行操作xml文件

a.遍历xml文档的所有内容

from xml.etree import ElementTree as ET

############ 解析方式一 ############
"""
# 打开文件,读取XML内容
str_xml = open('xo.xml', 'r').read()

# 将字符串解析成xml特殊对象,root代指xml文件的根节点
root = ET.XML(str_xml)
"""
############ 解析方式二 ############

# 直接解析xml文件
tree = ET.parse("xo.xml")

# 获取xml文件的根节点
root = tree.getroot()


### 操作

# 顶层标签
print(root.tag)


# 遍历XML文档的第二层
for child in root:
    # 第二层节点的标签名称和标签属性
    print(child.tag, child.attrib)
    # 遍历XML文档的第三层
    for i in child:
        # 第二层节点的标签名称和内容
        print(i.tag,i.text)
View Code

b.遍历xml中指定的节点

from xml.etree import ElementTree as ET

############ 解析方式一 ############
"""
# 打开文件,读取XML内容
str_xml = open('xo.xml', 'r').read()

# 将字符串解析成xml特殊对象,root代指xml文件的根节点
root = ET.XML(str_xml)
"""
############ 解析方式二 ############

# 直接解析xml文件
tree = ET.parse("xo.xml")

# 获取xml文件的根节点
root = tree.getroot()


### 操作

# 顶层标签
print(root.tag)


# 遍历XML中所有的year节点
for node in root.iter('year'):
    # 节点的标签名称和内容
    print(node.tag, node.text)
View Code

c.修改节点内容

由于修改节点时,均是在内存中进行,其不会影响文件中的内容。所以,如果想要修改,则需要重新将内存中的内容写到新文件

from xml.etree import ElementTree as ET

############ 解析方式一 ############

# 打开文件,读取XML内容
str_xml = open('xo.xml', 'r').read()

# 将字符串解析成xml特殊对象,root代指xml文件的根节点
root = ET.XML(str_xml)

############ 操作 ############

# 顶层标签
print(root.tag)

# 循环所有的year节点
for node in root.iter('year'):
    # 将year节点中的内容自增一
    new_year = int(node.text) + 1
    node.text = str(new_year)

    # 设置属性
    node.set('name', 'alex')
    node.set('age', '18')
    # 删除属性
    del node.attrib['name']


############ 保存文件 ############
tree = ET.ElementTree(root)
tree.write("newnew.xml", encoding='utf-8')

解析字符串方式,修改,保存
解析字符串方式,修改,保存
from xml.etree import ElementTree as ET

############ 解析方式二 ############

# 直接解析xml文件
tree = ET.parse("xo.xml")

# 获取xml文件的根节点
root = tree.getroot()

############ 操作 ############

# 顶层标签
print(root.tag)

# 循环所有的year节点
for node in root.iter('year'):
    # 将year节点中的内容自增一
    new_year = int(node.text) + 1
    node.text = str(new_year)

    # 设置属性
    node.set('name', 'alex')
    node.set('age', '18')
    # 删除属性
    del node.attrib['name']


############ 保存文件 ############
tree.write("newnew.xml", encoding='utf-8')

解析文件方式,修改,保存
解析文件方式,修改,保存

d.删除节点

from xml.etree import ElementTree as ET

############ 解析字符串方式打开 ############

# 打开文件,读取XML内容
str_xml = open('xo.xml', 'r').read()

# 将字符串解析成xml特殊对象,root代指xml文件的根节点
root = ET.XML(str_xml)

############ 操作 ############

# 顶层标签
print(root.tag)

# 遍历data下的所有country节点
for country in root.findall('country'):
    # 获取每一个country节点下rank节点的内容
    rank = int(country.find('rank').text)

    if rank > 50:
        # 删除指定country节点
        root.remove(country)

############ 保存文件 ############
tree = ET.ElementTree(root)
tree.write("newnew.xml", encoding='utf-8')

解析字符串方式打开,删除,保存
解析字符串方式打开,删除,保存
from xml.etree import ElementTree as ET

############ 解析文件方式 ############

# 直接解析xml文件
tree = ET.parse("xo.xml")

# 获取xml文件的根节点
root = tree.getroot()

############ 操作 ############

# 顶层标签
print(root.tag)

# 遍历data下的所有country节点
for country in root.findall('country'):
    # 获取每一个country节点下rank节点的内容
    rank = int(country.find('rank').text)

    if rank > 50:
        # 删除指定country节点
        root.remove(country)

############ 保存文件 ############
tree.write("newnew.xml", encoding='utf-8')

 解析文件方式打开,删除,保存
解析文件方式打开,删除,保存

3.创建xml文档

from xml.etree import ElementTree as ET


# 创建根节点
root = ET.Element("famliy")


# 创建节点大儿子
son1 = ET.Element('son', {'name': '儿1'})
# 创建小儿子
son2 = ET.Element('son', {"name": '儿2'})

# 在大儿子中创建两个孙子
grandson1 = ET.Element('grandson', {'name': '儿11'})
grandson2 = ET.Element('grandson', {'name': '儿12'})
son1.append(grandson1)
son1.append(grandson2)


# 把儿子添加到根节点中
root.append(son1)
root.append(son1)

tree = ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)

创建方式(一)
创建方式(一)
from xml.etree import ElementTree as ET

# 创建根节点
root = ET.Element("famliy")


# 创建大儿子
# son1 = ET.Element('son', {'name': '儿1'})
son1 = root.makeelement('son', {'name': '儿1'})
# 创建小儿子
# son2 = ET.Element('son', {"name": '儿2'})
son2 = root.makeelement('son', {"name": '儿2'})

# 在大儿子中创建两个孙子
# grandson1 = ET.Element('grandson', {'name': '儿11'})
grandson1 = son1.makeelement('grandson', {'name': '儿11'})
# grandson2 = ET.Element('grandson', {'name': '儿12'})
grandson2 = son1.makeelement('grandson', {'name': '儿12'})

son1.append(grandson1)
son1.append(grandson2)


# 把儿子添加到根节点中
root.append(son1)
root.append(son1)

tree = ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)

创建方式(二)
创建方式(二)
from xml.etree import ElementTree as ET


# 创建根节点
root = ET.Element("famliy")


# 创建节点大儿子
son1 = ET.SubElement(root, "son", attrib={'name': '儿1'})
# 创建小儿子
son2 = ET.SubElement(root, "son", attrib={"name": "儿2"})

# 在大儿子中创建一个孙子
grandson1 = ET.SubElement(son1, "age", attrib={'name': '儿11'})
grandson1.text = '孙子'


et = ET.ElementTree(root)  #生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True, short_empty_elements=False)

 创建方式(三)
创建方式(三)

由于原生保存xml是默认无缩进,如果想要设置缩进的话,需要修改保存方式:

from xml.etree import ElementTree as ET
from xml.dom import minidom


def prettify(elem):
    """将节点转换成字符串,并添加缩进。
    """
    rough_string = ET.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="\t")

# 创建根节点
root = ET.Element("famliy")


# 创建大儿子
# son1 = ET.Element('son', {'name': '儿1'})
son1 = root.makeelement('son', {'name': '儿1'})
# 创建小儿子
# son2 = ET.Element('son', {"name": '儿2'})
son2 = root.makeelement('son', {"name": '儿2'})

# 在大儿子中创建两个孙子
# grandson1 = ET.Element('grandson', {'name': '儿11'})
grandson1 = son1.makeelement('grandson', {'name': '儿11'})
# grandson2 = ET.Element('grandson', {'name': '儿12'})
grandson2 = son1.makeelement('grandson', {'name': '儿12'})

son1.append(grandson1)
son1.append(grandson2)


# 把儿子添加到根节点中
root.append(son1)
root.append(son1)


raw_str = prettify(root)

f = open("xxxoo.xml",'w',encoding='utf-8')
f.write(raw_str)
f.close()

写入缩进
写入缩进

4.命名空间

from xml.etree import ElementTree as ET

ET.register_namespace('com',"http://www.company.com") #some name

# build a tree structure
root = ET.Element("{http://www.company.com}STUFF")
body = ET.SubElement(root, "{http://www.company.com}MORE_STUFF", attrib={"{http://www.company.com}hhh": "123"})
body.text = "STUFF EVERYWHERE!"

# wrap it in an ElementTree instance, and save as XML
tree = ET.ElementTree(root)

tree.write("page.xml",
           xml_declaration=True,
           encoding='utf-8',
           method="xml")

命名空间
命名空间

requests模块

  Python标准库中提供了:urllib等模块以供http请求,但是,它的API太渣了。他是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。

  requests是使用apache2 licensed许可证的基于Python开发的HTTP库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网络请求时,变得美好了许多,使用Requests可以轻而易举的完成浏览器可有的任何操作

1.安装模块

  pip3 install requests

2.使用模块

# 1、无参数实例
 
import requests
 
ret = requests.get('https://github.com/timeline.json')
 
print(ret.url)
print(ret.text)
 
 
 
# 2、有参数实例
 
import requests
 
payload = {'key1': 'value1', 'key2': 'value2'}
ret = requests.get("http://httpbin.org/get", params=payload)
 
print(ret.url)
print(ret.text)

GET请求
GET请求
# 1、基本POST实例
 
import requests
 
payload = {'key1': 'value1', 'key2': 'value2'}
ret = requests.post("http://httpbin.org/post", data=payload)
 
print(ret.text)
 
 
# 2、发送请求头和数据实例
 
import requests
import json
 
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
 
ret = requests.post(url, data=json.dumps(payload), headers=headers)
 
print(ret.text)
print(ret.cookies)

 POST请求
POST请求
requests.get(url, params=None, **kwargs)
requests.post(url, data=None, json=None, **kwargs)
requests.put(url, data=None, **kwargs)
requests.head(url, **kwargs)
requests.delete(url, **kwargs)
requests.patch(url, data=None, **kwargs)
requests.options(url, **kwargs)
 
# 以上方法均是在此方法的基础上构建
requests.request(method, url, **kwargs)

 其他请求
其他请求

更多requests模块相关的文档见:http://cn.python-requests.org/zh_CN/latest/

3.http请求和xml实例

实例:检测QQ账号是否在线

import urllib
import requests
from xml.etree import ElementTree as ET

# 使用内置模块urllib发送HTTP请求,或者XML格式内容
"""
f = urllib.request.urlopen('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=630571017')
result = f.read().decode('utf-8')
"""


# 使用第三方模块requests发送HTTP请求,或者XML格式内容
r = requests.get('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508')
result = r.text

# 解析XML格式内容
node = ET.XML(result)

# 获取内容
if node.text == "Y":
    print("在线")
else:
    print("离线")

检测QQ账号是否在线
检测QQ账号是否在线

实例:查看火车停靠信息

import urllib
import requests
from xml.etree import ElementTree as ET

# 使用内置模块urllib发送HTTP请求,或者XML格式内容
"""
f = urllib.request.urlopen('http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=')
result = f.read().decode('utf-8')
"""

# 使用第三方模块requests发送HTTP请求,或者XML格式内容
r = requests.get('http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=')
result = r.text

# 解析XML格式内容
root = ET.XML(result)
for node in root.iter('TrainDetailInfo'):
    print(node.find('TrainStation').text,node.find('StartTime').text,node.tag,node.attrib)

查看火车停靠信息
查看火车停靠信息

实例:查看天气信息

import requests

response = requests.get("http://www.weather.com.cn/data/sk/101010100.html")
response.encoding = "utf-8"
result = response.text
print(result)
查看天气信息

configparser模块

configparser模块用于处理特定格式的文件,其本质上是利用open来操作文件

#指定格式

#注释
;注释2

[nick]           #节点
age = 18         #
gender = ning    #
dearm = girl     #

[jenny]          #节点
age = 21         #
gender = jia     #

1.获取所有节点

1 import configparser
2  
3 con = configparser.ConfigParser()
4 con.read("ini",encoding="utf-8")
5  
6 result = con.sections()
7 print(result)

2.获取指定节点下所有的键值对

1 import configparser
2  
3 con = configparser.ConfigParser()
4 con.read("ini",encoding="utf-8")
5  
6 result = con.items("nick")
7 print(result)

3.获取指定节点下所有的键

1 import configparser
2  
3 con = configparser.ConfigParser()
4 con.read("ini",encoding="utf-8")
5  
6 ret = con.options("nick")
7 print(ret)

4.获取指定节点下指定key的值

 1 import configparser
 2  
 3 con = configparser.ConfigParser()
 4 con.read("ini",encoding="utf-8")
 5  
 6 v = con.get("nick","age")
 7 v = con.get("nick","gender")
 8 v = con.get("jenny","age")
 9 v = con.get("jenny","gender")
10 print(v)

5.检查、删除、添加节点

 1 #检查、删除、添加节点
 2 import configparser
 3  
 4 con = configparser.ConfigParser()
 5 con.read("ini",encoding="utf-8")
 6  
 7 #检查
 8 has_sec = con.has_section("nick")
 9 print(has_sec)
10  
11 #添加节点
12 con.add_section("car")
13 con.write(open("ini","w"))
14  
15 #删除节点
16 con.remove_section("car")
17 con.write(open("ini","w"))

6.检查、删除、设置指定组内的键值对

 1 #检查、删除、设置指定组内的键值对
 2 import configparser
 3  
 4 con = configparser.ConfigParser()
 5 con.read("ini",encoding="utf-8")
 6  
 7 #检查
 8 hac_opt = con.has_option("nick","age")
 9 print(hac_opt)
10  
11 #删除
12 con.remove_option("nick","dearm")
13 con.write(open("ini","w"))
14  
15 #设置
16 con.set("nick","dearm","girl")
17 con.write(open("ini","w"))

logging模块

用于便捷记录日志且线程安全的模块

1.单日志文件

 1 import logging
 2  
 3 logging.basicConfig(filename="log.log",
 4                     format="%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s",
 5                     datefmt="%Y-%m-%d %H:%M:%S %p",
 6                     level=logging.INFO)
 7  
 8 logging.critical("critical")
 9 logging.fatal("fatal")
10 logging.error("error")
11 logging.warn("warn")
12 logging.warning("warning")
13 logging.info("info")
14 logging.debug("debug")
15 logging.log(8,"log")

日志等级

"""
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
"""

只有【当前写等级】大于【日志等级】时,日志文件才被记录

2.多文件日志

对于上述记录日志的功能,只能将日志记录在单文件中,如果想要设置多个日志文件,logging.basicConfig将无法完成,需要自定义文件和日志操作对象

 1 # 定义文件
 2 file_1_1 = logging.FileHandler('l1_1.log', 'a')
 3 fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s")
 4 file_1_1.setFormatter(fmt)
 5 
 6 file_1_2 = logging.FileHandler('l1_2.log', 'a')
 7 fmt = logging.Formatter()
 8 file_1_2.setFormatter(fmt)
 9 
10 # 定义日志
11 logger1 = logging.Logger('s1', level=logging.ERROR)
12 logger1.addHandler(file_1_1)
13 logger1.addHandler(file_1_2)
14 
15 
16 # 写日志
17 logger1.critical('1111')
18 
19  日志(一)
日志(一)
 1 # 定义文件
 2 file_2_1 = logging.FileHandler('l2_1.log', 'a')
 3 fmt = logging.Formatter()
 4 file_2_1.setFormatter(fmt)
 5 
 6 # 定义日志
 7 logger2 = logging.Logger('s2', level=logging.INFO)
 8 logger2.addHandler(file_2_1)
 9 
10 日志(二)
日志(二)

如上述创建的两个日志对象

  · 当使用logger1写日志时,会将相应的内容写入l1_1.log和l1_2.log文件中

  · 当使用logger2写日志时,会将相应的内容写入l2_1.log文件中

 1 import os
 2 import logging
 3 from logging.handlers import TimedRotatingFileHandler
 4 
 5     base = os.path.abspath(os.path.dirname(__file__))
 6     logfile = os.path.join(base, 'test', 'testlog')
 7     handler = TimedRotatingFileHandler(filename=logfile, when='MIDNIGHT',
 8                                                       interval=1, backupCount=365)
 9     handler.suffix = "%Y%m%d.log"
10     handler.setFormatter(logging.Formatter('%(asctime)s\t%(levelname)-8s\t%(message)s'))
11     handler.setLevel(logging.DEBUG)
12     apipartnerlogger = logging.getLogger(logfile)
13     apipartnerlogger.addHandler(handler)
14     apipartnerlogger.setLevel(logging.INFO)
15 
16 记录日志及按天切割实例
日志

 

posted @ 2016-12-15 11:33  AWM  阅读(120)  评论(0编辑  收藏