1.urllib2可以接受一个Request对象,并以此可以来设置一个URL的headers,但是urllib只接收一个URL。

2.urllib模块可以提供进行urlencode的方法,该方法用于GET查询字符串的生成,urllib2的不具有这样的功能。

1) urllib2.urlopen(url[, data][, timeout])

3.urlopen方法是urllib2模块最常用也最简单的方法,它打开URL网址,url参数可以是一个字符串url或者是一个Request对象。

4.urlopen方法也可通过建立了一个Request对象来明确指明想要获取的url。

2) class urllib2.Request(url[, data][, headers][, origin_req_host][, unverifiable])

Request类是一个抽象的URL请求。5个参数的说明如下

  URL——是一个字符串,其中包含一个有效的URL。

  data——是一个字符串,指定额外的数据发送到服务器,如果没有data需要发送可以为“None”。这些数据需要被以标准的格式编码(encode),然后作为一个数据参数传送给Request对象。Encoding是在urlib模块中完成的,而不是在urlib2中完成的。

  headers——是字典类型,头字典可以作为参数在request时直接传入,也可以把每个键和值作为参数调用add_header()方法来添加。标准的headers组成是(Content-Length, Content-Type and Host),只有在Request对象调用urlopen()或者OpenerDirector.open()时加入。

origin_req_host——是RFC2965定义的源交互的request-host。默认的取值是cookielib.request_host(self)。这是由用户发起的原始请求的主机名或IP地址。例如,如果请求的是一个HTML文档中的图像,这应该是包含该图像的页面请求的request-host。

  unverifiable ——代表请求是否是无法验证的,它也是由RFC2965定义的。默认值为false。一个无法验证的请求是,其用户的URL没有足够的权限来被接受。例如,如果请求的是在HTML文档中的图像,但是用户没有自动抓取图像的权限,unverifiable的值就应该是true。

import urllib
import urllib2
url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {'name' : 'Michael Foord',
'location' : 'Northampton',
'language' : 'Python' }
headers = { 'User-Agent' : user_agent }
data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()

5.调用urlopen函数对请求的url返回一个response对象。这个response类似于一个file对象,所以用.read()函数可以操作这个response对象。

response对象的几个常用的方法:

  geturl() — 返回检索的URL资源,这个是返回的真正url,通常是用来鉴定是否重定向的。

  info() — 返回页面的原信息就像一个字段的对象, 如headers,它以mimetools.Message实例为格式(可以参考HTTP Headers说明)。

  getcode() — 返回响应的HTTP状态代码。

    当不能处理一个response时,urlopen抛出一个URLError(对于python APIs,内建异常如,ValueError, TypeError 等也会被抛出。)
  HTTPError是HTTP URL在特别的情况下被抛出的URLError的一个子类。

  URLError——handlers当运行出现问题时(通常是因为没有网络连接也就是没有路由到指定的服务器,或在指定的服务器不存在),抛出这个异常.它是IOError的子类.这个抛出的异常包括一个‘reason’ 属性,他包含一个错误编码和一个错误文字描述。

  HTTPError——HTTPError是URLError的子类。每个来自服务器HTTP的response都包含“status code”. 有时status code不能处理这个request. 默认的处理程序将处理这些异常的responses。例如,urllib2发现response的URL与你请求的URL不同时也就是发生了重定向时,会自动处理。对于不能处理的请求, urlopen将抛出HTTPError异常. 典型的错误包含‘404’ (没有找到页面), ‘403’ (禁止请求),‘401’ (需要验证)等。它包含2个重要的属性reason和code。

   如果我们想同时处理HTTPError和URLError,因为HTTPError是URLError的子类,所以应该把捕获HTTPError放在URLError前面,如不然URLError也会捕获一个HTTPError错误,代码参考如下:

import urllib2
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.reason
except urllib2.URLError,e:
  print 'We failed to reach a server.'
  print 'Reason: ', e.reason
else:
  # everything is fine
  response.read()

代码改进如下:

import urllib2
req = urllib2.Request('http://www.python.org/fish.html')
try:
  response=urllib2.urlopen(req)
except urllib2.URLError as e:
  if hasattr(e, 'reason'):
    #HTTPError and URLError all have reason attribute.
    print 'We failed to reach a server.'
    print 'Reason: ', e.reason
  elif hasattr(e, 'code'):
    #Only HTTPError has code attribute.
    print 'The server couldn\'t fulfill the request.'
    print 'Error code: ', e.code
  else:
  # everything is fine
  response.read()

# Table mapping response codes to messages; entries have the
# form {code: (shortmessage, longmessage)}.
responses = {
100: ('Continue', 'Request received, please continue'),
101: ('Switching Protocols',
'Switching to new protocol; obey Upgrade header'),

200: ('OK', 'Request fulfilled, document follows'),
201: ('Created', 'Document created, URL follows'),
202: ('Accepted',
'Request accepted, processing continues off-line'),
203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
204: ('No Content', 'Request fulfilled, nothing follows'),
205: ('Reset Content', 'Clear input form for further input.'),
206: ('Partial Content', 'Partial content follows.'),

300: ('Multiple Choices',
'Object has several resources -- see URI list'),
301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
302: ('Found', 'Object moved temporarily -- see URI list'),
303: ('See Other', 'Object moved -- see Method and URL list'),
304: ('Not Modified',
'Document has not changed since given time'),
305: ('Use Proxy',
'You must use proxy specified in Location to access this '
'resource.'),
307: ('Temporary Redirect',
'Object moved temporarily -- see URI list'),

400: ('Bad Request',
'Bad request syntax or unsupported method'),
401: ('Unauthorized',
'No permission -- see authorization schemes'),
402: ('Payment Required',
'No payment -- see charging schemes'),
403: ('Forbidden',
'Request forbidden -- authorization will not help'),
404: ('Not Found', 'Nothing matches the given URI'),
405: ('Method Not Allowed',
'Specified method is invalid for this server.'),
406: ('Not Acceptable', 'URI not available in preferred format.'),
407: ('Proxy Authentication Required', 'You must authenticate with '
'this proxy before proceeding.'),
408: ('Request Timeout', 'Request timed out; try again later.'),
409: ('Conflict', 'Request conflict.'),
410: ('Gone',
'URI no longer exists and has been permanently removed.'),
411: ('Length Required', 'Client must specify Content-Length.'),
412: ('Precondition Failed', 'Precondition in headers is false.'),
413: ('Request Entity Too Large', 'Entity is too large.'),
414: ('Request-URI Too Long', 'URI is too long.'),
415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
416: ('Requested Range Not Satisfiable',
'Cannot satisfy request range.'),
417: ('Expectation Failed',
'Expect condition could not be satisfied.'),

500: ('Internal Server Error', 'Server got itself in trouble'),
501: ('Not Implemented',
'Server does not support this operation'),
502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
503: ('Service Unavailable',
'The server cannot process the request due to a high load'),
504: ('Gateway Timeout',
'The gateway server did not receive a timely response'),
505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
}

python urllib2与urllib的更多相关文章

  1. python学习之----urllib与urllib2的区分

    urllib 还是urllib2 ? 如果你用过Python 2.x 里的urllib2 库,可能会发现urllib2 与urllib 有些不同. 在Python 3.x 里,urllib2 改名为u ...

  2. python urllib2/urllib实现

    urllib2和urllib是Python中的两个内置模块,要实现HTTP功能,实现方式是以urllib2为主,urllib为辅 urllib2提供一个基础函数urlopen,通过向指定的url发出请 ...

  3. python urllib2使用心得

    python urllib2使用心得 1.http GET请求 过程:获取返回结果,关闭连接,打印结果 f = urllib2.urlopen(req, timeout=10) the_page = ...

  4. python urllib2 模拟网站登陆

    python urllib2 模拟网站登陆 1. 可用浏览器先登陆,然后查看网页源码,分析登录表单 2. 使用python urllib2,cookielib 模拟网页登录 import urllib ...

  5. python urllib2详解及实例

    urllib2是Python的一个获取URLs(Uniform Resource Locators)的组件.他以urlopen函数的形式提供了一个非常简单的接口, 这是具有利用不同协议获取URLs的能 ...

  6. python2.x urllib2和urllib的使用

    1.最简单用法 urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,...) import urllib2 import ur ...

  7. python爬虫之urllib库(一)

    python爬虫之urllib库(一) urllib库 urllib库是python提供的一种用于操作URL的模块,python2中是urllib和urllib2两个库文件,python3中整合在了u ...

  8. python urllib2库的简单总结

    urllib2的简单介绍参考网址:http://www.voidspace.org.uk/python/articles/urllib2.shtml Fetching URLsThe simplest ...

  9. python urllib2介绍

    urllib2是Python的一个获取URLs(Uniform Resource Locators)的组件.他以urlopen函数的形式提供了一个非常简单的接口, 这是具有利用不同协议获取URLs的能 ...

随机推荐

  1. c# winform 视频转字符动画

    以上是大图展示, 原理比较简单,附件下载带了一个分辨率比较小的txt动画.   音乐删除了music.mp3,  如果需要自己下载一首歌曲,然后放在根目录名称“music.mp3”就可以了. 附件点我 ...

  2. HTML知识点总结之表单元素

    网页不可能是纯静态的,没有任何的交互功能:绝大多数的网站都有表单元素的使用.表单提供了一个浏览者和网站交互的途径,比如用户注册登录,用户留言等功能. form form元素只是一个数据获取元素的容器, ...

  3. VSCode好用的Python插件及配置

    MS Python插件. 这是微软官方的Python插件,已经自带很多功能.下面是插件功能描述,其中部分内容我做了翻译. a)        Linting (Prospector, Pylint,  ...

  4. Error:C:\Users\issuser\AndroidStudioProjects\SQLiteDemo1\.gradle\buildOutputCleanup\cache.properties (系统找不到指定的文件。)

    android studio报下图中的这个错误的解决办法: 解决办法: 1.删除掉下图中标记的2个文件夹 2.将下图标记的文件的文件名重命名,把最后的后缀.lock去掉,因为加上了这个后缀,所以提示找 ...

  5. 利用JParticles制作粒子

    JParticles 2.0发布,打造炫酷的粒子 一. 介绍 JParticles 2.0发布之前叫Particleground.js, 相信有在用的朋友应该不会陌生, 关于1.x的介绍可以看这里 二 ...

  6. 常见的VPS虚拟化架构:OpenVZ、Xen、Hyper-V、KVM、VMWare OpenVZ

    OpenVZ OpenVZ特点是,它是直接调用母服务器的内核,所以会导致部分软件无法使用,以及部分内核文件是无法修改. OpenVZ适用人群:新手.低预算客户 OpenVZ注意事项:资源不是自己独有的 ...

  7. 在虚拟机中安装metasploit官方攻防模拟器

    首先我们要在windwos下载安装perl环境.下载地址: http://pan.baidu.com/s/1i3GLKAp 然后我们安装 点击next 我同意,next next next,然后他会安 ...

  8. [bzoj1969] [Ahoi2005]LANE 航线规划

    tarjan.并查集.树状数组.树链剖分. 时间倒流,变删边为加边. 先求一波边双联通分量,缩点. 题目保证最后还是整张图联通的..所以就是一棵树. 现在的操作就是,将路径上的边权置0(加边时),查询 ...

  9. hdu_1029_hash/map

    http://acm.hdu.edu.cn/showproblem.php?pid=1029 太水了,一次过,直接上代码吧,只想说最愚蠢的hash都要比map快! #include<cstdio ...

  10. c++(线性队列)

    这里的线性结构实际上指的就是连续内存的意思,只不过使用“线性”这个词显得比较专业而已.前面一篇博客介绍了现象结构的处理方法,那么在这个基础之上我们是不是添加一些属性形成一种新的数据结构类型呢?答案是肯 ...