python核心类库:urllib使用详解
python版本:2.7.15
1.简单用法urllib.urlopen()
语法:
urllib.urlopen(url[, data[, proxies]]) :
打开一个url的方法,返回一个文件对象,然后可以进行类似文件对象的操作。
示例代码:
googleResponse = urllib.urlopen('http://www.google.com.hk')
print 'http header:/n', googleResponse.info()
print 'http status:', googleResponse.getcode()
print 'url:', googleResponse.geturl()
# 读取html页面的第一行
firstLine = googleResponse.readline()
# 就像在操作本地文件
for line in googleResponse:
print line,
googleResponse.close()
urlopen返回对象提供方法:
- read() , readline() ,readlines() , fileno() , close() :这些方法的使用方式与文件对象完全一样
- info():返回一个httplib.HTTPMessage对象,表示远程服务器返回的头信息
- getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到
- geturl():返回请求的url
2.存储为文件urllib.urlretrieve()
语法:
urllib.urlretrieve(url[,filename[,reporthook[,data]]])
urlretrieve方法将url定位到的html文件下载到你本地的硬盘中。如果不指定filename,则会存为临时文件。
urlretrieve()返回一个二元组(filename,mine_hdrs)
临时存放:
filename = urllib.urlretrieve('http://www.google.com.hk/')
prtin type(filename)
# <type 'tuple'>
prtin filename[0]
# '/tmp/tmp8eVLjq'
print filename[1]
# <httplib.HTTPMessage instance at 0xb6a363ec>
存为本地文件:
filename = urllib.urlretrieve('http://www.google.com.hk/',filename='/home/python/google.html')
print type(filename)
# <type 'tuple'>
print filename[0]
# '/home/python/google.html'
print filename[1]
# <httplib.HTTPMessage instance at 0xb6e2c38c>
3.使用urllib实现post方法和get方法
需要用到urllib.urlencode(query)将URL中的参数键值对以连接符&划分
GET方法:
import urllib
params=urllib.urlencode({'name':'aaron','pwd':'123456','rem':0})
print params
# 'pwd=123456&name=aaron&rem=0'
f=urllib.urlopen("http://dev.xxx.com/login?%s" % params)
print f.read()
POST方法:
import urllib
parmas = urllib.urlencode({'name':'aaron','pwd':'123456','rem':0})
f=urllib.urlopen("http://dev.xxx.com/login",parmas)
f.read()
4.其它方法
urllib.urlcleanup()
清除由于urllib.urlretrieve()所产生的缓存
urllib.quote(url)和urllib.quote_plus(url)
将url数据获取之后,并将其编码,从而适用与URL字符串中,使其能被打印和被web服务器接受。
print urllib.quote('http://www.baidu.com')
# 'http%3A//www.baidu.com'
print urllib.quote_plus('http://www.baidu.com')
# 'http%3A%2F%2Fwww.baidu.com'
urllib.unquote(url)和urllib.unquote_plus(url)
与urllib.quote(url)和urllib.quote_plus(url)函数相反。
done!
最新文章
- 给定一个double类型的数组arr,其中的元素可正可负可0,返回子数组累乘的最大乘积。例如arr=[-2.5,4,0,3,0.5,8,-1],子数组[3,0.5,8]累乘可以获得最大的乘积12,所以返回12。
- Python全栈开发day6
- java安装教程
- nginx搭建高性能流媒体技术
- 推些C语言与算法书籍
- 1058: [ZJOI2007]报表统计 - BZOJ
- 为什么java不支持多重继承?
- iOS7 StatusBar 使用小结
- Arduino 各种模块篇 蓝牙模块 手机蓝牙控制Arduino LED灯
- SVN错误:Attempted to lock an already-locked dir的解决
- 自制操作系统Antz(15)——实现启动界面
- AX_CreateAndPostInventJournal
- བྱ་དེ་ཁྲུང་ཁྲུང་དཀར་པོ།།--洁白的仙鹤/仓央嘉措情歌--IPA--藏语
- [BUAA_SE_2017]第零次博客
- 【题解】 Codeforces Edu41 F. k-substrings (字符串Hash)
- P1262 间谍网络
- mysql主从复制以及读写分离
- 浙江省“一卡通”异地就医,C#调用省一卡通动态库
- vmware Esxi 回收Thin模式磁盘空间
- ECharts图表tooltip显示时超出canvas图层解决方法