urllib是python自带的一个抓取网页信息一个接口,他最主要的方法是urlopen(),是基于python的open()方法的。下面是主要说明:
urllib.urlopen('网址'):这里传入urlopen()的参数有特别说要求,要遵循一些网络协议,比如http,ftp,也就是说,在网址的开头必须要有http://这样的说明,如:urllib.urlopen('http://www.baidu.com'),要么就是本地文件,本地文件需要使用file关键字,比如urllib.urlopen('file:hello.py'),注意,这里的hello.py是指的是当前的classpath所指定的内容,如果对hello.py这里有什么疑问那一定是python寻找classpath的顺序不是很清楚了,当然也可以直接写全部路径,urllib.urlopen('file:F:\pythontest\hello.py'),
import urllib f = urllib.urlopen('file:F:\pythontest\hello.py') a = f.read() print a
如果传入的参数正确,比如该网站可以访问,没有特殊情况(比如需要代理,被墙- -等),那么将返回一个类似于文件对象的对象。即上面代码中的f,f对象有的方法一些操作方法,使用dir(f):
['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', 'fileno', 'fp', 'geturl', 'headers', 'info', 'next', 'read', 'readline', 'readlines', 'url']
>>>f.geturl() 'F://pythontest//hello.py'
import urllib proxies = {'http':'http://***.***.***.***:1984'} filehandle = urllib.urlopen('http://www.需要代理才能访问的网站.com/',proxies = proxies) a = filehandle.read() print a
查看urllib的源码:
def urlopen(url, data=None, proxies=None): """urlopen(url [, data]) -> open file-like object""" global _urlopener if proxies is not None: opener = FancyURLopener(proxies=proxies) elif not _urlopener: opener = FancyURLopener() _urlopener = opener else: opener = _urlopener if data is None: return opener.open(url) else: return opener.open(url, data)

代理支持是python 2.3以后加入的.
这次先这样,下次记录urllib的urlretrieve方法