【Python】Python http编程:urllib包与http包详解
来源:互联网 发布:蒋方舟写作水平知乎 编辑:程序博客网 时间:2024/06/05 19:48
python自3.x版本推出之后,web端的编程更加方便。对于python的Internet方面的官方提供接口可以在Internet Protocols and Support栏目下查询。在该栏目下可以发现包括ftp(文件传输协议)、smtp(邮件协议)等相关的应用层的编程接口。除此之外,python对网络端的数据处理也提供了非常好的支持,具体内容可以参考Internet Data Handlingt。在该栏目中python对常用的ascii和json,还有一些其他的数据编解码都提供了很好的接口支持。不过,这些都不是我们本文的重点,我们这里是主要讨论Internet Protocols and Support下python对使用http协议的的web端开发相关的内容。当然如果有可能,还是建议使用更好的web开发框架,比如webpy、django,或者其他的请求协议框架比如Requests
文章分为三部分,第一部分是讲解python提供的库的支持,第二部分讲述简单的使用场景,第三部分是我认为有用的链接,包括官方的教程和一些深入的介绍的资料。
python库介绍
在web端编程主要使用的库有两个。
一个是和url请求与返回相关的包urllib,其主要包括:
- urllib.request for opening and reading URLs
- urllib.error containing the exceptions raised byurllib.request
- urllib.parse for parsing URLs
- urllib.robotparser for parsingrobots.txt files
- http.client is a low-level HTTP protocol client; for high-level URL opening useurllib.request
- http.server contains basic HTTP server classes based onsocketserver
- http.cookies has utilities for implementing state management with cookies
- http.cookiejar provides persistence of cookies
urllib库详解
req = urllib.request.Request("http://weibo.com/")data = urllib.request.urlopen(req)#data = urllib.request.urlopen("http://weibo.com/")for d in data.readlines(): print(str(d,encoding = "utf-8"))
def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, *, cafile=None, capath=None, cadefault=False): global _opener if cafile or capath or cadefault: if not _have_ssl: raise ValueError('SSL support not available') context = ssl._create_stdlib_context(cert_reqs=ssl.CERT_REQUIRED, cafile=cafile, capath=capath) https_handler = HTTPSHandler(context=context, check_hostname=True) opener = build_opener(https_handler) elif _opener is None: _opener = opener = build_opener() else: opener = _opener return opener.open(url, data, timeout)
httplib库详解
import http.clientconn = http.client.HTTPConnection("www.baidu.com")conn.request("GET", "/index.html")r1 = conn.getresponse()#返回的是HTTPResponse对象
应用示例
单纯一个请求
req = urllib.request.Request("http://weibo.com/")data = urllib.request.urlopen(req)for d in data.readlines(): print(str(d,encoding = "utf-8"))这是最简单的一种请求发出的方式,通过构造一个Request对象然后调用接口发出请求,读取返回数据,读取后的数据是字节的形式。最后把字节数据通过utf-8转化为字符串输出结果。
发送HEAD请求
req= urllib2.Request(url) req.get_method = lambda : 'HEAD' r = urllib2.urlopen(req)
使用代理
proxy_url="http://XXX.com:port/"proxy_handler = urllib.request.ProxyHandler({'http': proxy_url})opener = urllib.request.build_opener(proxy_handler)urllib.request.install_opener(opener)req = urllib.request.Request("http://weibo.com/")data = urllib.request.urlopen(req)这是使用代理的请求代码,通过提前声明一个代理,然后构造一个Handler,并把该handler在opener中声明,最后还有调用安装opener接口,用来覆盖掉默认的opener。这时候,当打开一个连接的时候,就会调用我们构造的opener,相应的当opener打开某个连接的时候,就可以调用代理handler处理具体的请求。在构造代理handler的时候需要一个字典,字典的key是说明代理的类型,本文是http;字典的value是代理的地址与端口号组成的字符串。
proxy = urllib2.ProxyHandler({'http': 'ip:port'}) opener = urllib2.build_opener(proxy) urllib2.install_opener(opener) r = urllib2.urlopen(url)
r是一个response的对象,可以通过print r.info()获取消息头信息。
传递参数
param= urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})param= param.encode('utf-8')request = urllib.request.Request("http://weib.com")request.add_header("Content-Type","application/x-www-form-urlencoded;charset=utf-8")data = urllib.request.urlopen(request, param)把要传递的参数以map的形式通过urlencode进行编码,然后通过utf-8再进行编码
附录
Use Python in the web:http://docs.python.org/3.2/howto/webservers.html
Using The urllib Package:http://docs.python.org/3.2/howto/urllib2.html
webpy:http://webpy.org/
Django:https://www.djangoproject.com/
- 【Python】Python http编程:urllib包与http包详解
- python包urllib名称
- python3 urllib包与http包的使用
- python基于http协议编程:httplib,urllib和urllib2
- python基于http协议编程:httplib,urllib和urllib2
- python基于http协议编程:httplib,urllib和urllib2
- python基于http协议编程:httplib,urllib和urllib2
- python基于http协议编程:httplib,urllib和urllib2
- python抓包截取http记录日志
- Python urllib,urllib2包学习笔记
- Python第三方包 requests还是urllib?
- 详解HTTP包
- http包 详解
- python的http请求模块urllib+requests
- 49.[Python]使用requests包进行HTTP交互方法详解
- Python闭包编程
- python函数对象与闭包详解
- python闭包详解
- 【Expression 序列化】WCF的简单使用及其Expression Lambada的序列化问题初步解决方案(四)——关于Guid的问题
- Perl抓取网页信息
- android精品开源项目
- 做管理者要让自己对具体业务细节多说不知道
- java.net.UnknownHostException 异常处理
- 【Python】Python http编程:urllib包与http包详解
- 如何将WEB-INF下的jsp页面插入在frameset中
- Android Fragment
- 《黑马程序员》 集合 collection、、Linklist、、Vector day14
- lua实现全排列
- Perl读写数据库数据
- java自学视频
- c实现vector
- android alarm类型