python模块之urllib2基本爬虫入门
来源:互联网 发布:淘宝qps 编辑:程序博客网 时间:2024/05/19 20:21
前言
笔者最近迷恋上了python,以前都是搞java爬虫,现在开始进行python下爬虫修炼。我使用的python版本都是python2.7,所有python,python3变化比较大,短时间不能切换过去。
什么是urllib2
python下一个HTTP 客户端库,该模块定义的函数和类用来获取URL(主要是HTTP的),他提供一些复杂的接口用于处理: 基本认证,重定向,Cookies等,详细如下:
- Proxy 的设置
- Timeout 设置
- 在 HTTP Request 中加入特定的 Header
- Redirect
- Cookie
- 使用 HTTP 的 PUT 和 DELETE 方法
- 得到 HTTP 的返回码
- Debug Log
httplib、urllib和urllib2区别
urllib和urllib2
urllib 和urllib2都是接受URL请求的相关模块,但是urllib2可以接受一个Request类的实例来设置URL请求的headers,urllib仅可以接受URL。
这意味着,你不可以伪装你的User Agent字符串等。
urllib提供urlencode方法用来GET查询字符串的产生,而urllib2没有。这是为何urllib常和urllib2一起使用的原因。
目前的大部分http请求都是通过urllib2来访问的httplib
httplib实现了HTTP和HTTPS的客户端协议,一般不直接使用,在更高层的封装模块中(urllib,urllib2)使用了它的http实现。来自:http://blog.csdn.net/dolphin_h/article/details/45296353
这里我说一点:在python3中urllib和urllib2合并为一个urllib库。
代码实例
# -*- coding: UTF-8 -*-#author:StarryTengimport urllib2import urlliburl = "http://music.163.com/#/song?id=280761" #网易云的一首歌request = urllib2.urlopen(url)#print request.read()#---------------------------------------------------------------values = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' }user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'headers = {'User-Agent' : user_agent, 'Content-Type' : 'application/json; charset=utf-8', 'Cache-Control' : 'no-cache' }data = urllib.urlencode(values)req = urllib2.Request(url, data)response = urllib2.urlopen(req)result = response.read()print result#-------------------------------------------------------------------req = urllib2.Request('http://www.python.org/fish.html')try: response=urllib2.urlopen(req)except urllib2.HTTPError,e: print 'The server couldn\'t fulfill the request.' print 'Error code: ',e.code print 'Error reason: ',e.reasonexcept urllib2.URLError,e: print 'We failed to reach a server.' print 'Reason: ', e.reasonelse: # everything is fine response.read()
(爬下来数据之后就是对数据进行匹配,筛选,可以用正则表达式,我不会正则,尴尬想到之前用java时候用过jsoup依赖,去看看python后没有,有的话,下篇博客就写soupl)
后记
这是python爬虫学习的一个最基本的模块,其实就是模拟http请求,后面应该还有更加全面的模块,以及框架(猜的,以以往学习的经验来说的)。哈哈,结束!
2017年 10月 07日 星期六 13:18:43 CST
- python模块之urllib2基本爬虫入门
- Python爬虫入门_之urllib2&&urllib
- python 爬虫入门(2) 爬虫基础知识 ; urllib 模块 ;urllib2 模块
- Python爬虫----爬虫入门(3)---urllib2
- 把玩之python爬虫urllib2
- Python爬虫之urllib2介绍
- python模块系列之-urllib2
- python模块学习之---- urllib2模块详解
- python模块之---- urllib2模块详解
- 把玩之python爬虫urllib2高级篇
- Python爬虫----爬虫入门(4)---urllib2 模拟登陆
- Python模块之---urllib,urllib2,httplib
- urllib2 模块基本运用
- 爬虫系列17.urllib2模块
- python urllib2模块介绍
- python urllib2模块
- Python的urllib2模块
- Python的urllib2模块
- Codeforces 868C Qualification Rounds
- centos虚拟机网络配置NAT模式和桥接模式总结
- 6.4OpenCV中值滤波
- linux系统基本命令(八)
- 制作一份手机录屏的 GIF 动态图片
- python模块之urllib2基本爬虫入门
- Python学习笔记:生成器与迭代器
- python中包的使用总结
- 制作打怪小游戏Kill Bill
- 一位数加法程序 加强版
- [备忘]xcode里的python
- Servlet
- OpenCV傅里叶变换
- 使用python发短信给自己的手机