python访问web的利器:urllib2
来源:互联网 发布:app生成器下载软件 编辑:程序博客网 时间:2024/05/01 03:36
使用Python访问网页主要有三种方式: urllib, urllib2, httplib
urllib比较简单,功能相对也比较弱,httplib简单强大,但好像不支持session
1. 最简单的页面访问
res=urllib2.urlopen(url)
print res.read()
2. 加上要get或post的数据
data={"name":"hank", "passwd":"hjz"}
urllib2.urlopen(url, urllib.urlencode(data))
3. 加上http头
header={"User-Agent": "Mozilla-Firefox5.0"}
urllib2.urlopen(url, urllib.urlencode(data), header)
使用opener和handler
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
4. 加上session
cj = cookielib.CookieJar()
cjhandler=urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cjhandler)
urllib2.install_opener(opener)
5. 加上Basic认证
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "http://www.163.com/"
password_mgr.add_password(None, top_level_url, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
6. 使用代理
proxy_support = urllib2.ProxyHandler({"http":"http://1.2.3.4:3128/"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
7. 设置超时
socket.setdefaulttimeout(5)
urllib比较简单,功能相对也比较弱,httplib简单强大,但好像不支持session
1. 最简单的页面访问
res=urllib2.urlopen(url)
print res.read()
2. 加上要get或post的数据
data={"name":"hank", "passwd":"hjz"}
urllib2.urlopen(url, urllib.urlencode(data))
3. 加上http头
header={"User-Agent": "Mozilla-Firefox5.0"}
urllib2.urlopen(url, urllib.urlencode(data), header)
使用opener和handler
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
4. 加上session
cj = cookielib.CookieJar()
cjhandler=urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cjhandler)
urllib2.install_opener(opener)
5. 加上Basic认证
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "http://www.163.com/"
password_mgr.add_password(None, top_level_url, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
6. 使用代理
proxy_support = urllib2.ProxyHandler({"http":"http://1.2.3.4:3128/"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
7. 设置超时
socket.setdefaulttimeout(5)
- python访问web的利器:urllib2
- python访问web的利器:urllib2
- python访问web的利器:urllib2
- 【Python】urllib2访问url
- Python的urllib2模块
- Python的urllib2模块
- Python的urllib2
- python urllib2的proxyhandler
- Python 的 urllib2
- Python-urllib2的使用
- python]用urllib2设置代理访问网页
- python urllib2的使用案例
- Python 的 urllib,urllib2,httplib
- python的urllib2 模块解析
- python的urllib和urllib2
- python urllib2库的用法
- python urllib2
- python urllib2
- 织梦5.7把互动中心修改成腾讯微博的方法
- PYTHON 代理POST
- dedecms5.7 文章不能发布解决方法
- ESMTP身份验证机制探索手记
- 正则表达式
- python访问web的利器:urllib2
- Unity3D的版本控制
- Python 标准库 urllib2 的使用细节
- c++ socket flex 中文 乱码
- Struts2常用标签总结
- HEVC中的几个重要概念
- Oracle索引_约束
- 学习经验
- struts2传递实体类参数