一、Python2 httplib
urllib、urllib2
二、python3urlliburllib发起请求
urllib进行url编码
简介:httplib实现了HTTP和HTTPS的客户端协议,一般不直接使用,在python更高层的封装模块中(urllib,urllib2)使用了它的http实现。
httplib实现http请求
[Python]
纯文本查看
复制代码
01 02 03 04 05 06 07 08 09 10 11 | import httplibhost = ‘www.baidu.com’ # 注意:不能带上协议port = 80# 获取HTTPConnection对象conn = httplib.HTTPConnection(host, port)# 发起请求conn.request("GET", "/")# 获取返回值res = conn.getresponse()print res.status # 状态码print res.read() # 返回结果 |
简介:urllib 和urllib2都是接受URL请求的相关模块,但是urllib2可以接受一个Request类的实例来设置URL请求的headers,urllib仅可以接受URL。
[Python]
纯文本查看
复制代码
1 2 3 4 5 6 7 8 9 | import urllib[/b]d = { "$count":"count", "$limit":"limit", "$offset":"offset", "$filter":None,}print urllib.urlencode(d)结果:%24offset=offset&%24limit=limit&%24filter=None&%24count=count |
[Python]
纯文本查看
复制代码
1 2 3 4 5 6 7 8 9 | import jsonimport urllibimport urllib2#get responsedata = json.dumps(body)conn = urllib2.Request(url, data, header)res = urllib2.urlopen(conn)print resprint res.read() |
二、python3urllib
简介:Python3中也有urllib和urllib3两个库,其中urllib几乎是Python2中urllib和urllib2两个模块的集合,所以我们最常用的urllib模块,而urllib3则作为一个拓展模块使用。
[Python]
纯文本查看
复制代码
1 2 3 4 | import urllibfrom urllib import requestres = request.urlopen("http://www.baidu.com")print(res.read()) |
urllib进行url编码
[Python]
纯文本查看
复制代码
1 2 3 4 5 6 | import urllibfrom urllib import parsed = {"a":"1","b":"2"}parse.urlencode(d)结果:'a=1&b=2' |
更多技术资讯可关注:itheimaGZ获取