python urllib urlopen()对象方法/代理的补充说明 python urllib urlopen()对象方法/代理的补充说明 urllib 是 python 自带的一个抓取网页信息一个接口,他最主要的方法是 urlopen(),是基于 python 的 open() 方法的。下面是主要说明: urllib.urlopen('网址') 这里传入urlopen()的参数有特别说要求,要遵循一些网络协议,比如http,ftp,也就是说,在网址的开头必须要有http://这样的说明,如:urllib.urlopen('http://www.baidu.com')。 要么就是本地文件,本地文件需要使用file关键字,比如 urllib.urlopen('file:nowamagic.py'),注意,这里的hello.py是指的是当前的classpath所指定的内容,如果对hello.py这里有什么疑问那一定是python寻找classpath的顺序不是很清楚了,当然也可以直接写全部路径,urllib.urlopen('file:F:\pythontest\nowamagic.py')。 打开 ftp 文件也是可以的,写法 urllib.urlopen(url='ftp://用户名:密码@ftp地址/') 等。 示例程序: import urllib f = urllib.urlopen('file:F:\pythontest\nowamagic.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'] 使用read()方法会将所有内容读取出来,并且同时f对象类似于先入先出的数据,在使用f.read()将得不到任何数据,也就是说,得到的数据在这个时候如果想在后面进行任何处理操作的话,需要另外定义一个对象来进行存储。如上例中的a。而info(),geturl()方法,也是基于f这个文档对象的,所以,使用 >>>f.geturl() 'F://pythontest//nowamagic.py' 接下来是urllib的代理设置: import urllib proxies = {'http':'http://***.***.***.***:1984'} filehandle = urllib.urlopen('http://www.需要代理才能访问的网站.com/',proxies = proxies) a = filehandle.read() print a 以上是最基本代理,即代理访问到该网站,并且能够获得该网站的内容。但是如果遇到需要登录,或者需要cookie等的网站呢? 查看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) 由上面urllib的urlopen的源码,可以看出,还可以传入一个data参数,data参数也应该是一个字典,因为在使用浏览器向服务器发送数据的时候,我们发送的就是字典类型的数据。 还有一点,就是代理支持是 python 2.3 以后加入的。 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!