《The Python Standard Library》——http模块阅读笔记1
官方文档:https://docs.python.org/3.5/library/http.html
偷个懒,截图如下:

即,http客户端编程一般用urllib.request库(主要用于“在这复杂的世界里打开各种url”,包括:authentication、redirections、cookies and more.)。
1. urllib.request—— Extensible library for opening URLs
使用手册,结合代码写的很详细:HOW TO Fetch Internet Resources Using The urllib Package
该模块提供的函数:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
urllib.request.install_opener(opener)
urllib.request.build_opener([handler, ...])
urllib.request.pathname2url(path)
urllib.request.url2pathname(path)
urllib.request.getproxies()
该模块提供的类:
class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
class urllib.request.OpenerDirector
class urllib.request.BaseHandler
class urllib.request.HTTPDefaultErrorHandler
class urllib.request.HTTPRedirectHandler
class urllib.request.HTTPCookieProcessor(cookiejar=None)
class urllib.request.ProxyHandler(proxies=None)
class urllib.request.HTTPPasswordMgr
还有很多,不一一列出了。。。
1.2 Request对象
下面的方法是Request提供的公共接口,所以它们可以被子类重写。同时,也提供了一些客户端可以查阅解析的请求的公共属性。
Request.full_url Request.type Request.host Request.origin_req_host #不包含端口号
Request.selector Request.data Request.unverifiable Request.method
Request.get_method() Request.add_header(key, val) Request.add_unredirected_header(key, header) Request.has_header(header) Request.remove_header(header)
Request.get_full_url() Request.set_proxy(host, type) Request.get_header(header_name, default=None) Request.header_items()
1.3 OpenerDirector Objects
有以下方法:
OpenerDirector.add_handler(handler)
OpenerDirector.open(url, data=None[, timeout])
OpenerDirector.error(proto, *args)
1.4 BaseHandler Objects
1.5 HTTPRedirectHandler Objects
1.6 HTTPCookieProcessor Objects
它只有一个属性:HTTPCookieProcessor.cookiejar ,所有的cookies都保存在http.cookiejar.CookeiJar中。
1.x 还有太多类,需要用时直接查看官方文档吧。。
EXamples
打开url读取数据:
>>> import urllib.request
>>> with urllib.request.urlopen('http://www.python.org/') as f:
... print(f.read(300))
...
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n\n\n<html
xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n\n<head>\n
<meta http-equiv="content-type" content="text/html; charset=utf-8" />\n
<title>Python Programming '
注意:urlopen返回一个bytes object(字节对象)。
>>> with urllib.request.urlopen('http://www.python.org/') as f:
... print(f.read(100).decode('utf-8'))
...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtm
向CGI的stdin发送数据流:
>>> import urllib.request
>>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi',
... data=b'This data is passed to stdin of the CGI')
>>> with urllib.request.urlopen(req) as f:
... print(f.read().decode('utf-8'))
...
Got Data: "This data is passed to stdin of the CGI"
CGI的另一端通过stdin接收数据:
#!/usr/bin/env python
import sys
data = sys.stdin.read()
print('Content-type: text/plain\n\nGot Data: "%s"' % data)
Use of Basic HTTP Authentication:
import urllib.request
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
uri='https://mahler:8092/site-updates.py',
user='klem',
passwd='kadidd!ehopper')
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)
urllib.request.urlopen('http://www.example.com/login.html')
添加HTTP头部:
import urllib.request
req = urllib.request.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
# Customize the default User-Agent header value:
req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)')
r = urllib.request.urlopen(req)
OpenerDirector automatically adds a User-Agent header to every Request. To change this:
import urllib.request
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open('http://www.example.com/')
Also, remember that a few standard headers (Content-Length, Content-Type and Host) are added when the Request is passed to urlopen() (or OpenerDirector.open()).
GET:
>>> import urllib.request
>>> import urllib.parse
>>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> url = "http://www.musi-cal.com/cgi-bin/query?%s" % params
>>> with urllib.request.urlopen(url) as f:
... print(f.read().decode('utf-8'))
POST:
>>> import urllib.request
>>> import urllib.parse
>>> data = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> data = data.encode('ascii')
>>> with urllib.request.urlopen("http://requestb.in/xrbl82xr", data) as f:
... print(f.read().decode('utf-8'))
The following example uses an explicitly specified HTTP proxy, overriding environment settings:
>>> import urllib.request
>>> proxies = {'http': 'http://proxy.example.com:8080/'}
>>> opener = urllib.request.FancyURLopener(proxies)
>>> with opener.open("http://www.python.org") as f:
... f.read().decode('utf-8'
The following example uses no proxies at all, overriding environment settings:
>>> import urllib.request
>>> opener = urllib.request.FancyURLopener({})
>>> with opener.open("http://www.python.org/") as f:
... f.read().decode('utf-8')
《The Python Standard Library》——http模块阅读笔记1的更多相关文章
- Python Standard Library
Python Standard Library "We'd like to pretend that 'Fredrik' is a role, but even hundreds of vo ...
- Python 日期时间处理模块学习笔记
来自:标点符的<Python 日期时间处理模块学习笔记> Python的时间处理模块在日常的使用中用的不是非常的多,但是使用的时候基本上都是要查资料,还是有些麻烦的,梳理下,便于以后方便的 ...
- Python语言中对于json数据的编解码——Usage of json a Python standard library
一.概述 1.1 关于JSON数据格式 JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 46 ...
- The Python Standard Library
The Python Standard Library¶ While The Python Language Reference describes the exact syntax and sema ...
- 《The Python Standard Library》——http模块阅读笔记2
http.server是用来构建HTTP服务器(web服务器)的模块,定义了许多相关的类. 创建及运行服务器的代码一般为: def run(server_class=HTTPServer, handl ...
- 《The Python Standard Library》——http模块阅读笔记3
http.cookies — HTTP state management http.cookies模块定义了一系列类来抽象cookies这个概念,一个HTTP状态管理机制.该模块支持string-on ...
- python os os.path模块学习笔记
#!/usr/bin/env python #coding=utf-8 import os #创建目录 os.mkdir(r'C:\Users\Silence\Desktop\python') #删除 ...
- Python Standard Library 学习(一) -- Built-in Functions 内建函数
内建函数列表 Built-in Functions abs() divmod() input() open() staticmethod() all() enumerate() int() ord() ...
- Python内置模块和第三方模块
1.Python内置模块和第三方模块 内置模块: Python中,安装好了Python后,本身就带有的库,就叫做Python的内置的库. 内置模块,也被称为Python的标准库. Python 2.x ...
随机推荐
- 编写高质量代码改善C#程序的157个建议——建议61:避免在finally内撰写无效代码
建议61:避免在finally内撰写无效代码 在阐述建议之前,需要先提出一个问题:是否存在一种打破try-finally执行顺序的情况,答案是:不存在(除非应用程序本身因为某些很少出现的特殊情况在tr ...
- 编写高质量代码改善C#程序的157个建议——建议41:实现标准的事件模型
建议41:实现标准的事件模型 上一建议中,我们实现了一个带事件通知的文件传输类FileUploader.虽然已经满足需求,但却不符合C#的编码规范,查看EventHandler的原型声明: publi ...
- 编写高质量代码改善C#程序的157个建议——建议34:为泛型参数设定约束
建议34:为泛型参数设定约束 “约束”这个词可能会引起歧义,有些人肯能认为对泛型参数设定约束是限制参数的使用,实际情况正好相反.没有“约束”的泛型参数作用很有限,倒是“约束”让泛型参数具有了更多的行为 ...
- sqlserver跨服务器查询
两个sqlserver数据库在不同的服务器上如何插入数据哪? EXEC sp_configure RECONFIGURE EXEC sp_configure RECONFIGURE INSERT IN ...
- 连续bezier曲线的实现
需求场景 一系列的坐标点,划出一条平滑的曲线 3次Bezier曲线 基本上大部分绘图工具都实现了3次Bezier曲线,4个点确定一条3次Bezier曲线.以html5中的canvas为例 let ct ...
- Django 学习:为窗体加上防机器人的验证机制(验证码功能)
这里我们使用 django-simple-captcha 模块,官方介绍如下:https://github.com/mbi/django-simple-captcha 一键安装: pip instal ...
- 【bzoj2500】幸福的道路 树形dp+单调队列
Description 小T与小L终于决定走在一起,他们不想浪费在一起的每一分每一秒,所以他们决定每天早上一同晨练来享受在一起的时光. 他们画出了晨练路线的草图,眼尖的小T发现可以用树来描绘这个草图. ...
- gluster peer probe: failed: Probe returned with unknown errno 107解决方法
当在glusterfs中将服务器加到存储池中,及运行”gluster peer probe server”命令, 遇到peer probe: failed: Probe returned with u ...
- Java面向对象之异常(异常处理方式)
一.基础概念 (1)异常:Java程序在运行时期发生的不正常情况. Java就按照面向对象的思想对不正常情况进行描述和对象的封装. (2)异常问题分类: (Throwable:定义对于问题共性的功能. ...
- 【BZOJ3417】[POI2013]MOR-Tales of seafaring (最短路SPFA)
[POI2013]MOR-Tales of seafaring 题目描述 一个n点m边无向图,边权均为1,有k个询问 每次询问给出(s,t,d),要求回答是否存在一条从s到t的路径,长度为d 路径不必 ...