python模块之urllib2基本爬虫入门

来源:互联网 发布:淘宝qps 编辑:程序博客网 时间:2024/05/19 20:21

前言

笔者最近迷恋上了python,以前都是搞java爬虫,现在开始进行python下爬虫修炼。我使用的python版本都是python2.7,所有python,python3变化比较大,短时间不能切换过去。

什么是urllib2

python下一个HTTP 客户端库,该模块定义的函数和类用来获取URL(主要是HTTP的),他提供一些复杂的接口用于处理: 基本认证,重定向,Cookies等,详细如下:

  1. Proxy 的设置
  2. Timeout 设置
  3. 在 HTTP Request 中加入特定的 Header
  4. Redirect
  5. Cookie
  6. 使用 HTTP 的 PUT 和 DELETE 方法
  7. 得到 HTTP 的返回码
  8. 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

原创粉丝点击