《python爬虫》学习笔记:urllib2库的使用
2015-12-03 21:34
513 查看
最简单的爬虫代码
import urllib2 response=urllib2.urlopen("http://www.baidu.com") print response.read()
上面的等价代码
#encoding=utf-8 import urllib2 request=urllib2.Request("http://www.baidu.com")#构造一个request对象实例 response=urllib2.urlopen(request) print response.read()
POST和GET的使用
先看post提交数据的方法,如下:#encoding=utf-8 #post 方式传送数据 import urllib import urllib2 values={'username':'154943046@qq.com','password':'xxxx'} data=urllib.urlencode(values)#将提交的字典编码 url="https://passport.csdn.net/account/login?from=http://my.csdn.net/my/mycsdn" request=urllib2.Request(url,data) response=urllib2.urlopen(request) print response.read()
get方式的传送数据
#encoding=utf-8 import urllib import urllib2 #python中字典的另外一种写法 values={} values["username"]="154943046@qq.com" values["password"]="XXXX" data=urllib.urlencode(values) url="https://passport.csdn.net/account/login" geturl=url+"?"+data#get方式传送数据 print geturl request=urllib2.Request(geturl) response=urllib2.urlopen(request) print response.read()
设置请求头
#encoding=utf-8 #设置请求头 import urllib import urllib2 user_agent="Mozilla/5.0 (Windows NT 6.1)" referer="http://www.zhihu.com/" header={"User-Agent":user_agent,"Referer":referer} url="http://www.zhihu.com/" values={"username":"wuranghao","password":"xxxx"} data=urllib.urlencode(values) request=urllib2.Request(url ,data ,header) response=urllib2.urlopen(request) print response.read()
URLError和HTTPError
#encoding=utf-8 #访问错误的URL的抛异常的处理 #首先解释下URLError可能产生的原因: # 网络无连接,即本机无法上网 # 连接不到特定的服务器 # 服务器不存在 import urllib2 url="http://wuranghao.com" request=urllib2.Request(url) try: response=urllib2.urlopen(request) except urllib2.URLError,e: print e.reason #输出 [Errno 11004] getaddrinfo failed
#encoding=utf-8 #HTTPError的讲解:HTTPError是URLError的子类,在你利用urlopen方法发出一个请求时, #服务器上都会对应一个应答对象response,其中它包含一个数字”状态码”。 import urllib2 url="http://www.xingjiakmite.com" request=urllib2.Request(url) try: response=urllib2.urlopen(request) except urllib2.HTTPError,e: if hasattr(e,"code"): print e.code if hasattr(e,"reason"): print e.reason except urllib2.URLError,e: if hasattr(e,"reson"): print e.reason else: print "OK"
相关文章推荐
- Spark编程指南(Python版)
- LeetCode解题报告--Next Permutation
- 《Python程序设计》在亚马逊京东当当互动出版网淘宝全面上架
- (python)下载秒拍美拍视频
- 《Python程序设计基础》在亚马逊当当京东互动出版网淘宝等各大书店上架
- python write出现 Non-character array cannot be interpreted as character buffer.
- 详解python linecache模块读取文件的方法
- Python利用结巴分词进行中文分词
- 机器学习实战python版 朴素贝叶斯示例 垃圾邮件分类 从个人广告中获取趋于趋向
- Python 英文分词
- Python Ajax爬虫
- python 简单爬虫实现
- windows下安装Twisted Python
- 机器学习工具安装(python)
- 趣学Python-教孩子学编程--第十一章
- Python程序运行时间计算
- 一句话冒泡
- Python challenge 3 - urllib & re
- [python]类
- python cookbook