urllib模块

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路径转换成本地路径;


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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

THMAIL

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值