python的urllib2 模块解析
来源:互联网 发布:关键词点击软件 编辑:程序博客网 时间:2024/05/16 05:17
python是蜘蛛之王,蜘蛛离不开urllib。 urllib2 是urllib 的另一个版本,有很多改进。 听说内部代码也好了很多。
urllib2是python自带的一个访问网页和本地文件的库。 简单使用如下:
访问一个网址:
import urllib2
f=urllib2.urlopen("http://www.jeapedu.com")
buf = f.read()
读一个本地文件:
import urllib2
f=urllib2.urlopen('file:./a.txt')
buf=f.read()
如何获取库有那些函数或者类:
>>> dir(f)
['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', 'code', 'fileno', 'fp', 'getcode', 'geturl', 'headers', 'info', 'next', 'read', 'readline', 'readlines', 'url']
>>>
中文地址解析:¶
h4 = u'http://www.baidu.com?w=测试'
h4=h4.encode('utf-8')
urllib2.urlopen(h4)
最好用正确的编码转换一下。 上面的例子如果不用转换的函数处理一下网址,会导致urlopen 失败。
分类操作¶
FTP
handler = urllib2.FTPHandler()
request = urllib2.Request(url='ftp://ftp.ubuntu.com/')
opener = urllib2.build_opener(handler)
f = opener.open(request)
print f.read()
如果需要用户名和密码:
urllib2.Request(url='ftp://用户名:密码@ftp地址/')
HTTP
handler = urllib2.HTTPHandler()
request = urllib2.Request(url='http://ftp.ubuntu.com/')
opener = urllib2.build_opener(handler)
f = opener.open(request)
print f.read()
支持 headers
#coding=utf-8
import urllib2
request = urllib2.Request(url='http://192.168.2.201:8000/hd.txt')
request.add_header('Accept-encoding', 'gzip')
f = urllib2.urlopen(request)
print f.read()
0 0
- python的urllib2 模块解析
- Python的urllib2模块
- Python的urllib2模块
- python urllib2模块介绍
- python urllib2模块
- python urllib2模块介绍
- python urllib2模块介绍
- python urllib2模块学习
- python urllib2模块介绍
- python urllib2模块
- python urllib2模块介绍
- Python urllib2模块
- Python笔记:urllib2模块
- Python API 翻译-urllib2模块
- python urllib2模块技术参考
- python调用httplib,urllib2模块
- python urllib2模块使用方法总结
- python模块urllib2详解一
- [bfs] zoj 3865 Superbot
- 三大主流ETL工具选型
- Android之CursorAdapter用法
- C标准库文件之string.c文件
- Java编程思想重点笔记
- python的urllib2 模块解析
- java线程相关
- Ubuntu 无法拖拽复制
- 能上google的hosts更新2015-04-13
- How to deploy iOS apps to the iPhone via the command line
- iOS开发:创建真机调试证书
- [MFC] 脚本错误:对象不支持此属性或方法
- C语言自学笔记4(循环)
- iOS新浪微博客户端开发(3)——主界面搭建与动画