专栏名称: Python开发者
人生苦短,我用 Python。伯乐在线旗下账号「Python开发者」分享 Python 相关的技术文章、工具资源、精选课程、热点资讯等。
目录
相关文章推荐
Python爱好者社区  ·  YYDS!《大模型教材》PDF下载 ·  3 天前  
Python爱好者社区  ·  这估计是双非高校被黑的最惨的一次。获得杰青的 ... ·  5 天前  
Python爱好者社区  ·  算法备案通过了,说说踩过的坑 ·  1 周前  
Python开发者  ·  深度学习六十年简史 ·  1 周前  
51好读  ›  专栏  ›  Python开发者

Python 互联网数据处理模块介绍

Python开发者  · 公众号  · Python  · 2017-04-08 19:30

正文

(点击上方蓝字,快速关注我们)


来源:磁针石 

my.oschina.net/u/1433482/blog/675551

如有好文章投稿,请点击 → 这里了解详情


互联网无处不在。即使是很小的,一次性使用的脚本都经常与远程服务进行交互以发送或接收数据。 Python有丰富的Web协议库,非常适合用于编程的基于Web服务的服务器和客户端编程。


urlparse处理URL字符串。


urllib和更新的urllib2可以访问web资源,但是urllib2更容易扩展且urllib2.Request可自定义请求头。HTTP POST发送二进制数据通常使用base64编码。

robotparser用于处理网站机器人。


使用BaseHTTPServer可自定义Web服务器,回话状态可以基于Cookie。

uuid用于生成资源标识符。


基于web的远程调用,json在客户端和服务器都使用。比如xmlrpclib和xmlrpclib。


python web 客户端测试 相关模块


web客户端


- 标准模块:httplib

- 标准模块:urllib

- 标准模块:urllib2

- 外部模块 mechanize:Stateful programmatic web browsing.

  • 最近更新:2011-03-31。

  • 月下载量:38441。

  • 从perl WWW::Mechanize而来,兼容urllib2。


- 外部模块 spynner:Programmatic web browsing module with AJAX support for Python.

  • 最近更新:2013-07-16。

  • 月下载量:1192 。

  • 基于PyQT和WebKit,支持Javascript,AJAX,及其他WebKit可以处理的内容,比如 (Flash, SVG, …),利用了JQuery,用于在不适用GUI的情况模拟浏览器,适用于爬虫和验收测试。


- 外部模块 PAMIE:基于pywin32,实现IE自动化

  • 最近更新:2009-03-06。

  • 版本:3.0

  • 月下载量:无。

  • 只适用于windows,主页http://sourceforge.net/projects/pamie,可能要翻墙。


- WebTest:Helper to test WSGI applications –推荐

  • 最近更新:2014-01-23。

  • 版本:2.0.14

  • 月下载量:58134。

  • This wraps any WSGI application and makes it easy to send test requests to that application, without starting up an HTTP server.This provides convenient full-stack testing of applications written with any WSGI-compatible framework.Full docs can be found at https://webtest.readthedocs.org/en/latest/。

  • 下载:https://pypi.python.org/pypi/WebTest。

  • 主页: http://webtest.pythonpaste.org/。


参考资料


  • Web Programming in Python https://wiki.python.org/moin/WebProgramming

  • Web Site Test Tools and Site Management Tools http://www.softwareqatest.com/qatweb1.html


python 标准模块介绍 – Base16, Base32, Base64 数据编码


简介


功能:RFC 3548: Base16, Base32, Base64 数据编码。转换二进制数据为适合明文协议传输的 ASCII 序列。转换 8bits 为每个字节包含 6,5 或 4bits 的有效数据,比如 SMTP, URL 的一部分或者 HTTP POST 的一部分。参考: RFC 3548。编码算法不同于 uuencode。


类型:标准库


相关模块:uu, binhex, uu, quopri


Base64 是一种基于 64 个可打印字符来表示二进制数据的表示方法。由于 2 的 6 次方等于 64,所以每 6个位元为一个单元,对应某个可打印字符。三个字节有 24 个位元,对应于 4 个 Base64 单元,即 3 个字节需要用 4 个可打印字符来表示。它可用来作为电子邮件的传输编码。在 Base64 中的可打印字符包括字母 A-Z、a-z、数字 0-9,这样共有 62 个字符,此外两个可打印符号在不同的系统中而不同。之后在 6 位的前面补两个 0,形成 8 位一个字节的形式。一些如 uuencode 的其他编码方法,和之后 binhex 的版本使用不同的64 字符集来代表 6 个二进制数字,但是它们不叫 Base64。


Base64 常用于在通常处理文本数据的场合,表示、传输、存储一些二进制数据。包括 MIME 的email,email via MIME,在 XML 中存储复杂数据。


Python Base64 模块提供了 RFC3548 中的数据编码和解码(转换二进制数据为适合明文协议传输的ASCII 序列,如 RFC3548 中指定。该标准定义Base16,Base32 和 Base64 算法,编码和解码的任意二进制字符串转换为文本字符串,这样就可以通过电子邮件安全发送,作为网址的一部分,或包含在 HTTP POST 请求中。


Base64 模块提供两个接口。新式接口支持使用三个字母的编码和解码的字符串对象。传统接口提供了编码和解码文件对象和字符串,但只使用了标准的 Base64 字母。传统接口这里不做介绍。


base64、 base32、 base16 可以分别编码转化 8 位字节为 6 位、 5 位、 4 位。 16,32,64 分别表示用多少个字符来编码。


更多 base64 的资料,参见

http://zh.wikipedia.org/wiki/Base64,http://tools.ietf.org/html/rfc822,http://tools.ietf.org/html/rfc1421,http://tools.ietf.org/html/rfc2045。


快速入门


请看 python 模块介绍中的实例:


>>> import base64

>>> encoded = base64.b64encode('data to be encoded')

>>> encoded

'ZGF0YSB0byBiZSBlbmNvZGVk'

>>> data = base64.b64decode(encoded)

>>> data

'data to be encoded'


base64.b64encode(s[, altchars]):使用 Base64 编码字符串。s 是要编码的字符串。altchars 是用来替换+和/的字符串,它们在 url 和文件系统中它们有特殊含义,通常需要替换。


base64.b64decode(s[, altchars]): 解码 Base64 编码的字符串。s 为要解码的字符串。altchars 和b64encode 相同。


• base64.standard_b64encode ( s ) : 参考 b64encode。

• base64.standard_b64decode ( s ) :参考 b64decode。


Base64 编码解码


Base64 编码解码


#!/usr/bin/env python

# encoding: utf-8

#

# Copyright (c) 2008 Doug Hellmann All rights reserved.

#

"""

"""

__version__ = "$Id$"

#end_pymotw_header

import base64

import textwrap

# Load this source file and strip the header.

with open(__file__, 'rt') as input:

raw = input.read()

initial_data = raw.split('#end_pymotw_header')[1]

encoded_data = base64.b64encode(initial_data)

num_initial = len(initial_data)

# There will never be more than 2 padding bytes.

padding = 3 - (num_initial % 3)

print '%d bytes before encoding' % num_initial

print 'Expect %d padding bytes' % padding

print '%d bytes after encoding' % len(encoded_data)

print

print encoded_data


➢执行结果thon base64_b64encode.py


$ python base64_b64encode.py

168 bytes before encoding

Expect 3 padding bytes

224 bytes after encoding

CgppbXBvcnQgYmFzZTY0CmltcG9ydCB0ZXh0d3JhcAoKIyBMb2FkIHRoaXMgc291cmNlIGZpbGUgYW5kIHN0cmlwIHRoZSBoZWFk

ZXIuCndpdGggb3BlbihfX2ZpbGVfXywgJ3J0JykgYXMgaW5wdXQ6CiAgICByYXcgPSBpbnB1dC5yZWFkKCkKICAgIGluaXRpYWxfZGF0

YSA9IHJhdy5zcGxpdCgn



Base64 编码的 4 个字节对应实际的 3 个字节,不足四个字节时,后面部分通常用等号填充。极端的情况下,一个字节需要用 4 个 Base64 编码来表示。


>>> import base64

>>> encoded = base64.b64encode('a')

>>> encoded

'YQ=='


Base64 解码参见快速入门部分介绍。


URL-Safe


•base64.urlsafe_b64encode(s):

•base64.urlsafe_b64decode(s):


Base64 默认会使用+和/, 但是这 2 个字符在 url 中也有特殊含义。使用 urlsafe 可以解决这个问题。 +替换为-, /替换为_。


import base64

encodes_with_pluses = chr(251) + chr(239)

encodes_with_slashes = chr(255) * 2

for original in [ encodes_with_pluses, encodes_with_slashes ]:

print 'Original

:', repr(original)

print 'Standard encoding:', base64.standard_b64encode(original)

print 'URL-safe encoding:', base64.urlsafe_b64encode(original)

print


➢执行结果


$ python base64_urlsafe.py

Original

: '\xfb\xef'

Standard encoding: ++8=

URL-safe encoding: --8=

Original

: '\xff\xff'

Standard encoding: //8=

URL-safe encoding: __8=


其他编码

Base32 包含 26 个大写字母和 2-7 的数字。

• base64.b32encode(s):使用 Base32 编码字符串。s 是要编码的字符串。
• base64.b32decode(s[, casefold[, map01]]):解码 Base32 编码的字符串。s 为要解码的字符串 。

casefold 表示是否允许小写字母。 map01 表示允许 0 表示 0,1 表示 L 。

import base64

original_string = 'This is the data, in the clear.'

print 'Original:', original_string

encoded_string = base64.b32encode(original_string)

print 'Encoded :', encoded_string

decoded_string = base64.b32decode(encoded_string)

print 'Decoded :', decoded_string<code class="hljs stylus">g


➢执行结果


$ python base64_base32.py

Original: This is the data, in the clear.

Encoded : KRUGS4ZANFZSA5DIMUQGIYLUMEWCA2LOEB2GQZJAMNWGKYLSFY======

Decoded : This is the data, in the clear.


Base16 包含 16 个 16 进制大写数字。类似的有 base64.b16encode(s) ,base64.b16decode(s[,casefold]) 。


import base64

original_string = 'This is the data, in the clear.'

print 'Original:', original_string

encoded_string = base64.b16encode(original_string)

print 'Encoded :', encoded_string

decoded_string = base64.b16decode(encoded_string)

print 'Decoded :', decoded_string<code class="hljs stylus">tring


➢执行结果


$ python base64_base16.py

Original: This is the data, in the clear.

Encoded : 546869732069732074686520646174612C20696E2074686520636C6561722E

Decoded : This is the data, in the clear.

Python3.4 中增加了 Ascii85 base85 支持 。这里暂不做详细介绍。函数如下:

base64.a85encode(s, *, foldspaces=False, wrapcol=0, pad=False, adobe=False)

base64.a85decode(s, *, foldspaces=False, adobe=False, ignorechars=b' tnrv')

base64.b85encode(s, pad=False)

base64.b85decode(b)


  • python2 官方网址:http://docs.python.org/2/library/base64.html

  • python3 官方网址:https://docs.python.org/3/library/base64.html

  • python 标准库 pymotw:http://pymotw.com/2/base64/index.html#module-base64


python标准模块介绍- binascii 二进制和ASCII转换


简介


binascii模块包含很多用来方法来转换二进制和各种ASCII编码的二进制表示法。通常不直接使用这些功能,而是使用封装模块,如uu, base64或binhex。binascii模块包含用C语言编写更快的低级功能,通常为高级模块所使用。


  • 功能:二进制和ASCII转换。

  • 类型:标准模块

  • 相关模块:

  1. base64 标准模块。

  2. binhex 标准模块。

  3. uu        标准模块。

  4. quopri  标准模块。


Uu编码


uu编码格式现在已经比较少使用(http://zh.wikipedia.org/wiki/Uuencode),相关函数binascii.a2b_uu(string)和binascii.b2a_uu(data)这里不做介绍。 更多资料参见:http://docs.python.org/2/library/uu.html


Binhex编码


Binhex用于Macintosh平台。这里暂不做介绍。相关函数有:binascii.rledecode_hqx(data) ,binascii.rlecode_hqx(data),binascii.b2a_hqx(data) ,binascii.crc_hqx(data, crc)。 更多资料参见:http://docs.python.org/2/library/uu.html


Base64编码


binascii.a2b_base64(string):转换的base64数据块为二进制,并返回二进制数据。一次可以传递多行。和base64. b64decode对应。 binascii.b2a_base64(data):转换二进制数据为一行base64编码的ASCII字符。返回字符串包含换行符。根据base64的标准data的长度最大为57。和base64. b64encode对应。 更多资料参见:http://docs.python.org/2/library/base64.html


QP码


Quoted-printable,或QP encoding,没有规范的中文译名,可译为“可打印字符引用编码”、“使用可打印字符的编码”。Quoted-printable是使用可打印的 ASCII字符 (如字母、数字与”=”)表示各种编码格式下的字符,以便能在7-bit数据通路上传输8-bit数据, 或者更一般地说在非8-bit clean媒体上正确处理数据。这被定义为MIME content transfer encoding,用于e-mail。


QP使用”=”开头的转义字符. 一般限制行宽为76,因为有些软件限制了行宽.


binascii.a2b_qp(string[, header]):转换引述打印数据块为二进制,并返回二进制数据。多行可以在同一时间被传递。如果可选参数头存在和真实,下划线将被解码为空格。


实际上,QP码是是把’\x00’转换成’=00’,也就是替换’\x’为’=’。


>>> s ='\x00='

>>> s = '=\x00hello'

>>> import binascii

>>> encoded = binascii.b2a_qp(s)

>>> encoded

'=3D=00hello'

>>> decoded = binascii.a2b_qp(encoded)

>>> print decoded

=hello

>>> print repr(decoded)

'=\x00hello'


CRC校验和


binascii.crc32(data[, crc]):计算的data 的32位校验和CRC- 32时,crc为初始CRC 。crc32与ZIP文件的校验和一致。


>>> print binascii.crc32("hello world")

222957957

>>> crc = binascii.crc32("hello")

>>> crc = binascii.crc32(" world", crc) & 0xffffffff

>>> print 'crc32 = 0x%08x' % crc

crc32 = 0x0d4a1185

>>> crc

222957957


为了保证跨平台,可以在crc结果上& 0xffffffff。原因如下:


Changed in version 2.6: The return value is in the range [-2**31, 2**31-1] regardless of platform. In the past the value would be signed on some platforms and unsigned on others. Use & 0xffffffff on the value if you want it to match Python 3 behavior.

Changed in version 3.0: The return value is unsigned and in the range [0, 2**32-1] regardless of platform.


二进制转换


binascii.b2a_hex(data)和binascii.hexlify(data):返回二进制数据的十六进制表示。每个字节被转换成相应的 2位十六进制表示形式。因此,得到的字符串是是原数据长度的两倍。 binascii.a2b_hex(hexstr) 和binascii.unhexlify(hexstr):从十六进制字符串hexstr返回二进制数据。是b2a_hex的逆向操作。 hexstr必须包含偶数个十六进制数字(可以是大写或小写),否则报TypeError。


>>> s = 'hello'

>>> b = b2a_hex(s)

>>> print b

68656c6c6f

>>> a2b_hex(b)

'hello'

>>> b = hexlify(s)

>>> print b

68656c6c6f

>>> unhexlify(b)

'hello'


其他实例


http://effbot.org/librarybook/binascii.htm有如下实例:


import binascii

text = "hello, mrs teal"

data = binascii.b2a_base64(text)

text = binascii.a2b_base64(data)

print text, "<=>", repr(data)

data = binascii.b2a_uu(text)

text = binascii.a2b_uu(data)

print text, "<=>", repr(data)

data = binascii.b2a_hqx(text)

text = binascii.a2b_hqx(data)[0]

print text, "<=>", repr(data)

# 2.0 and newerdata = binascii.b2a_hex(text)

text = binascii.a2b_hex(data)

print text, "<=>", repr(data)


执行结果:


# python test.py

hello, mrs teal <=> 'aGVsbG8sIG1ycyB0ZWFs\n'

hello, mrs teal <=> '/:&5L;&\\L(&UR

hello, mrs teal <=> 'D\'9XE\'mX)\'ebFb"dC@&X'

hello, mrs teal <=> '68656c6c6f2c206d7273207465616c'


另外单元测试的代码也可供参考:http://svn.python.org/projects/python/branches/tarek_sysconfig/Lib/test/test_binascii.py


参考资料


  • http://docs.python.org/2/library/binascii.html

  • http://effbot.org/librarybook/binascii.htm


看完本文有收获?请转发分享给更多人

关注「Python开发者」,提升Python技能