在Python中涉及到URL请求相关的操作涉及到模块有urllib,urllib2,requests,其中urllib和urllib2是Python自带的HTTP访问标准库,requsets是第三方库,需要自行安装。requests是第三方库,可以想到在使用起来它可能是最方便的一个。

urllib和urllib2

      urllib和urllib2模块都是跟url请求相关的,但是提供的功能是不同的。我们常用的urllib2的请求方式:

response = urllib2.urlopen('http://www.baidu.com')

在参数中可以传入url和request对象,传入request可以来设置URL请求的headers,可以伪装成浏览器(当请求的网站进行请求监测的时候),urllib是只能传入url的,这也是二者的差别之一:

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
request = urllib2.Request(url, headers={
'User-Agent': user_agent
})
response = urllib2.urlopen(request)

但是在urllib中一些方法是没有加入的urllib2当中的,在有些时候也是需要urllib的辅助,这些我还暂时不是很懂,等遇到的时候再深究下,例如涉及到unicode编码相关的是只能用urllib来处理的,这也是二者的差别之一。

在urllib2中openurl函数还有几个常用的参数:data、timeout,阻塞操作以秒为单位,data和request对象在Request类中说明。

Requset类有5个参数:url,data,headers,origin_req_host,unverifiable 。

  1. url不必说了就是我们要请求的url地址
  2. data是我们要向服务器提交的额外的数据,如果没有数据可以为None,请求如果是由数据的话那就是POST请求,这些数据需要以标准的格式编码然后传送给request对象。
  3. headers请求头,是一个字典类型的。它是告诉服务器请求的一些信息,例如像请求的浏览器信息,操作系统信息,cookie,返回信息格式,缓存,是否支持压缩等等,像一些反爬虫的网站会监测请求的类型,我们需要伪装成浏览器而不是直接发起请求,例如上面代码里的User-Agent
  4. origin_req_host是RFC2965定义的源交互的request-host。默认的取值是cookielib.request_host(self)。这是由用户发起的原始请求的主机名或IP地址。例如,如果请求的是一个HTML文档中的图像,这应该是包含该图像的页面请求的request-host。
  5. unverifiable代表请求是否是无法验证的,它也是由RFC2965定义的。默认值为false。一个无法验证的请求是,其用户的URL没有足够的权限来被接受。

我们在请求的时候不一定每次都是请求的成功的页面,如果请求url不正常报错也是需要做好判断处理的。

try:
response = urllib2.urlopen('http://www.baidu.com')
except urllib2.HTTPError as e:
print e.code
print e.reason
except urllib2.URLError as e:
print e.reason
else:
response.read()

当发生错误抛出异常我们可以捕获查看异常原因,获取请求的状态码。getcode()方法也可以获取请求状态码,附录:

# 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.'),
}

Requests

requests使用的是urllib3,继承了urllib2的所有特性,Requests支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自 动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码。

get请求

response = requests.get('http://www.baidu.com')
print response.text

post请求

response = requests.post('http://api.baidu.com', data={
'data': 'value'
})

定制headers

response = requests.get('http://www.baidu.com', headers={
'User-Agent': user_agent
})

response返回数据的相关操作:

r.status_code #响应状态码
    r.raw #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read() 读取
    r.content #字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩
    r.text #字符串方式的响应体,会自动根据响应头部的字符编码进行解码
    r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
特殊方法:
    r.json() #Requests中内置的JSON解码器
    r.raise_for_status() #失败请求(非200响应)抛出异常

----------------未完待续---------------

人生苦短之Python的urllib urllib2 requests的更多相关文章

  1. python中urllib, urllib2,urllib3, httplib,httplib2, request的区别

    permike原文python中urllib, urllib2,urllib3, httplib,httplib2, request的区别 若只使用python3.X, 下面可以不看了, 记住有个ur ...

  2. Python使用urllib,urllib3,requests库+beautifulsoup爬取网页

    Python使用urllib/urllib3/requests库+beautifulsoup爬取网页 urllib urllib3 requests 笔者在爬取时遇到的问题 1.结果不全 2.'抓取失 ...

  3. 【Python爬虫实战--1】深入理解urllib;urllib2;requests

    摘自:http://1oscar.github.io/blog/2015/07/05/%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3urllib;urllib2;reques ...

  4. python中 urllib, urllib2, httplib, httplib2 几个库的区别

    转载 摘要: 只用 python3, 只用 urllib 若只使用python3.X, 下面可以不看了, 记住有个urllib的库就行了 python2.X 有这些库名可用: urllib, urll ...

  5. urllib,urllib2,requests对比

    #coding:utf-8 import urllib2 import urllib import httplib import socket import requests #实现以下几个方面内容: ...

  6. 三十一、python中urllib和requests包详解

    A.urllibimport urllibimport urllib.requestimport json '''1.loads,dumpsjson.loads():将字符串转化成python的基础数 ...

  7. python爬虫 urllib模块url编码处理

    案例:爬取使用搜狗根据指定词条搜索到的页面数据(例如爬取词条为‘周杰伦'的页面数据) import urllib.request # 1.指定url url = 'https://www.sogou. ...

  8. python urllib urllib2

    区别 1) urllib2可以接受一个Request类的实例来设置URL请求的headers,urllib仅可以接受URL.这意味着,用urllib时不可以伪装User Agent字符串等. 2) u ...

  9. Python 网络请求模块 urllib 、requests

    Python 给人的印象是抓取网页非常方便,提供这种生产力的,主要依靠的就是 urllib.requests这两个模块. urlib 介绍 urllib.request 提供了一个 urlopen 函 ...

随机推荐

  1. codevs——3344 迷宫

    3344 迷宫  时间限制: 1 s  空间限制: 32000 KB  题目等级 : 黄金 Gold 题解       题目描述 Description 小刚在迷宫内,他需要从A点出发,按顺序经过B, ...

  2. FMDB支持的事务类型

    FMDB支持的事务类型   在数据库中,事务可以保证数据操作的完整性.当存在大量并发操作,容易出现死锁问题.在SQLite中,为了解决该问题,提供三种事务模式,分别为DEFFERED.IMMEDIAT ...

  3. Codeforces Gym 100203E bits-Equalizer 贪心

    原题链接:http://codeforces.com/gym/100203/attachments/download/1702/statements.pdf 题解 考虑到交换可以减少一次操作,那么可以 ...

  4. Jena+fuseki

    1.下载apache-jena-3.1.0.tar.gz,这个可以将ttl三元组文件或者xml文件加载 进入bin目录,执行./tdbloader2 --loc /path/for/database ...

  5. 【redis】5.spring boot项目中,直接在spring data jpa的Repository层使用redis +redis注解@Cacheable直接在Repository层使用,报错问题处理Null key returned for cache operation

    spring boot整合redis:http://www.cnblogs.com/sxdcgaq8080/p/8028970.html 首先,明确一下问题的场景 之前在spring boot整合re ...

  6. Spring 与 MyBatis 整合

    一.实验介绍 1.1 实验内容 本节课程将整合 Spring 和 MyBatis,并采用 Junit 进行单元测试. 1.2 实验知识点 Spring - MyBatis 整合 Junit 单元测试 ...

  7. 浅析 rand7生成rand10 方法 之 思想篇(一)

    [问题描写叙述] rand7是一个能生成1-7的随机数.要求利用rand7生成1-10的随机数. [算法思想] 1.组合数学方法 第1次 1 2 3 4 5 6 7 之中用rand7取一个数 第2次从 ...

  8. Android API Guides---Services

    服务 在该文献 基础 声明在清单服务 创建一个启动的服务 扩展IntentService类 扩展服务类 启动服务 停止服务 创建绑定服务 将通知发送给用户 执行在前台服务 管理服务生命周期 实施生命周 ...

  9. ArcGIS 10.1系列产品 升级安装至 ArcGIS 10.2

    概要 分享ArcGIS10.1系列产品(包括desktop.engine.server)升级到ArcGIS10.2的过程,并提供安装ArcGIS10.2安装的详细文档下载链接和crack需要的文件: ...

  10. js 数组的迭代

    es5新增加的迭代方法(every,filter,forEach,map,some) arr1 = [1,2,3,4,5,6]; 1,every(); every() 方法使用指定函数检测数组中的所有 ...