python学习2:urllib2
2016-03-30 11:59
627 查看
打开指定URL,捕捉超时异常
定制HTTP头
POST请求
自定义opener,debuglevel=1可以打印debug数据
cookie
def urlopen(): url = "http://www.sina.com/no-exist" try: s = urllib2.urlopen(url, timeout=3) except urllib2.HTTPError, e: print(e) else: print(s.read()) s.close()
定制HTTP头
def request(): headers = {"User-Agent": "Mozilla/5.0", "X-my-header": "my value"} url = "http://blog.kamidox.com" req = urllib2.Request(url, headers=headers) s = urllib2.urlopen(req) print(s.read(100)) print(req.headers) s.close()
POST请求
def request_post_debug(): data = {"username": "snow", "password": "xxxxxx"} headers = {"User-Agent": "Mozilla/5.0", "Content-Type": "plain/text"} req = urllib2.Request("http://www.douban.com", data=urllib.urlencode(data), headers=headers) opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)) s = opener.open(req) print(s.read(100)) s.close()
自定义opener,debuglevel=1可以打印debug数据
def install_debug_handler(): opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1), urllib2.HTTPSHandler(debuglevel=1)) urllib2.install_opener(opener) install_debug_handler()
cookie
import cookielib def handle_cookie(): cookiejar = cookielib.CookieJar() hander = urllib2.HTTPCookieProcessor(cookiejar=cookiejar) opener = urllib2.build_opener(hander, urllib2.HTTPHandler(debuglevel=1)) s = opener.open("http://www.douban.com") print(s.read(100)) s.close() print("#" * 80) print(cookiejar._cookies) print("#" * 80) # 第二次访问会包含cookie s = opener.open("http://www.douban.com") print(s.read(100)) s.close()
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法