urllib模块

来源:互联网 发布:java接口里面的方法 编辑:程序博客网 时间:2024/06/05 09:05

1、urllibopen(url, data=None, proxies=None, context=None)

urlopen函数将会返回一个文本对象,可以像操作文本对象一样对其使用readline,read,readlines等操作,注意,不能进行写操作,只能读。data是post数据,没有就留空

例子:

>>> import urllib>>> f = urllib.urlopen('http://www.google.com.hk/')>>> firstLine = f.readline()   #读取html页面的第一行>>> firstLine'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage"><head><meta content="/images/google_favicon_128.png" itemprop="image"><title>Google</title><script>(function(){\n'

2、urlretrieve(url, filename=None, reporthook=None, data=None, context=None)

urlretrieve方法将url定位到的html文件下载到你本地的硬盘中。如果不指定filename,则会存为临时文件。

urlretrieve()返回一个二元组(filename,mine_hdrs)

临时存放:

>>> filename = urllib.urlretrieve('http://www.google.com.hk/')>>> type(filename)<type 'tuple'>>>> filename[0]'/tmp/tmp8eVLjq'>>> filename[1]<httplib.HTTPMessage instance at 0xb6a363ec>

存为本地文件:

>>> filename = urllib.urlretrieve('http://www.google.com.hk/',filename='/home/dzhwen/python文件/Homework/urllib/google.html')>>> type(filename)<type 'tuple'>>>> filename[0]'/home/dzhwen/python\xe6\x96\x87\xe4\xbb\xb6/Homework/urllib/google.html'>>> filename[1]<httplib.HTTPMessage instance at 0xb6e2c38c>

3.urllib.urlcleanup()

无参数,清除由于urllib.urlretrieve()所产生的缓存。


4.urllib.quote(url)和urllib.quote_plus(url)

将url数据获取之后,并将其编码,从而适用与URL字符串中,使其能被打印和被web服务器接受。

>>> urllib.quote('http://www.baidu.com')'http%3A//www.baidu.com'>>> urllib.quote_plus('http://www.baidu.com')'http%3A%2F%2Fwww.baidu.com'

urllib.quote_plus(url),与urllib.quote类似,但这个方法用’+’来替换’ ‘,而quote用’%20’来代替’ ‘

5.urllib.unquote(url)和urllib.unquote_plus(url)

与4的函数相反。


6.urllib.urlencode(query)

将URL中的键值对以连接符&划分

这里可以与urlopen结合以实现post方法和get方法:

GET方法:

>>> import urllib>>> params=urllib.urlencode({'spam':1,'eggs':2,'bacon':0})>>> params'eggs=2&bacon=0&spam=1'>>> f=urllib.urlopen("http://python.org/query?%s" % params)>>> print f.read()

POST方法:

>>> import urllib>>> parmas = urllib.urlencode({'spam':1,'eggs':2,'bacon':0})>>> f=urllib.urlopen("http://python.org/query",parmas)>>> f.read()
7、localhost()

返回localhost的ip,如:127.0.0.1

8、thishost()

返回当前主机的ip(应该是你上网所连接的路由器ip,我这里连得是校园网,返回的ip也是校园网登陆路由的ip)

9、

  • urllib.pathname2url(path):将本地路径转换成url路径;
  • urllib.url2pathname(path):将url路径转换成本地路径;


还有许多类和函数,并不是很常用,以后再看,可以参考官档和源代码




1 0
原创粉丝点击