发送请求

使用Requests发送网络请求很简单

  1. #首先要导入requests库
  2. import requests
  3. #返回一个Response对象
  4. r=requests.get('https://github.com/timeline.json')
  5. #由此可以看出来Requests的API十分简单,
  6. #post请求
  7. r=requests.post('http://httpbin.org/post')
  8. #Put请求,delete请求,head请求,options请求
  9. r=requests.put('http://httpbin.org/put')

传递URL参数

一般的get传递参数方法是将数据与url地址用?连起来。

Requests库允许使用params关键字参数,以一个dict来提供这些参数。

  1. import requests
  2. payload={'key1':'value1','key2':'value2'}
  3. r=requests.get('http://httpbin.org/get',params=payload)
  4. print(r.url)#可以看出response对象由url属性
  1. http://httpbin.org/get?key1=value1&key2=value2

响应内容

通过Response的text属性,我们可以读取服务器响应的内容。并且Requests会自动解码来自服务器的内容。

  1. import requests
  2. r=requests.get('https://github.com/timeline.json')
  3. r.text#已经经过自动解码
  1. '{"message":"Hello there, wayfaring stranger. If you’re reading this then you probably didn’t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"}'
  1. r.encoding
  2. #通过encoding属性显示响应的编码,并且可以改变编码属性。可以使用自定义的编码
  1. 'utf-8'

二进制响应内容

以字节的方式访问请求响应体

  1. r.content#未解码的内容,
  1. b'{"message":"Hello there, wayfaring stranger. If you\xe2\x80\x99re reading this then you probably didn\xe2\x80\x99t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.","documentation_url":"https://developer.github.com/v3/activity/events/#list-public-events"}'
  1. #Requests会自动解码gzip和deflate传输编码的响应数据。
  2. #举例,以请求返回的二进制数据创建一张图片
  3. from PIL import Image
  4. from io import BytesIO
  5. i=Image.open(BytesIO(r.content))

JSON响应内容

  1. import requests
  2. r=requests.get('https://github.com/timeline.json')
  3. r.json()
  1. {'documentation_url': 'https://developer.github.com/v3/activity/events/#list-public-events',
  2. 'message': 'Hello there, wayfaring stranger. If you’re reading this then you probably didn’t see our blog post a couple of years back announcing that this API would go away: http://git.io/17AROg Fear not, you should be able to get what you need from the shiny new Events API instead.'}

定制请求头headers

所有的header必须是string、bytestring或者unicode

  1. url='https://api.github.com/some/endpoint'
  2. headers={'user-agent':'my-app/0.0.1'}
  3. r=requests.get(url,headers=headers)

复杂的POST请求

  1. payload={'key1':'value1','key2':'value2'}
  2. #这里还可以讲dict替换成元祖列表,尤其在表单中多个元素使用同一key的时候。
  3. #还可以将data=替换成json=,传入json对象。
  4. r=requests.post('http://httpbin.org/post',data=payload)
  5. print(r.text)
  1. {
  2. "args": {},
  3. "data": "",
  4. "files": {},
  5. "form": {
  6. "key1": "value1",
  7. "key2": "value2"
  8. },
  9. "headers": {
  10. "Accept": "*/*",
  11. "Accept-Encoding": "gzip, deflate",
  12. "Connection": "close",
  13. "Content-Length": "23",
  14. "Content-Type": "application/x-www-form-urlencoded",
  15. "Host": "httpbin.org",
  16. "User-Agent": "python-requests/2.18.4"
  17. },
  18. "json": null,
  19. "origin": "36.102.236.202",
  20. "url": "http://httpbin.org/post"
  21. }

POST一个多部分编码的文件

  1. url='http://httpbin.org/post'
  2. files={'file':open('report.xls','rb')}#强烈建议使用二进制模式打开文件。
  3. r=requests.post(url,files=files)
  4. r.text#因为我们没有report.xls文件,所以不展示输出结果了

响应状态码

  1. r.status_code#获取状态码
  2. r.status_code==requests.codes.ok#内置由状态码查询对象
  3. #如果发送了一个错误请求,可以通过Response.raise_for_status()抛出异常,如果不是错误码,抛出None

响应头

  1. r.headers
  1. {'Date': 'Thu, 16 Nov 2017 13:01:18 GMT', 'Content-Type': 'application/json', 'Access-Control-Allow-Credentials': 'true', 'X-Processed-Time': '0.00141000747681', 'Via': '1.1 vegur', 'Content-Length': '465', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*', 'Server': 'meinheld/0.6.1', 'X-Powered-By': 'Flask'}

Cookie

  1. #访问cookie
  2. r.cookies['cookie_name']
  3. #发送cookie到服务器
  4. cookies=dict(cookies_are='workding')
  5. r.requests.get(url,cookies=cookies)
  6. r.text#会打印出cookie来
  7. #Cookie的返回对象为RequestsCookieJar,类似于字典,适合跨域名路径使用。
  8. jar=requests.cookies.RequestsCookieJar()
  9. jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
  10. jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
  11. url = 'http://httpbin.org/cookies'
  12. r = requests.get(url, cookies=jar)
  13. r.text

重定向与请求历史

除了HEAD,Requests会自动处理所有重定向。

可以使用history方法来追踪。

超时

设置timeout参数,以秒为单位。

timeout仅对连接过程有效,与响应体的下载无关。

会话对象

Session对象能够实现跨请求保持参数。并且在同一个session实例发出的所有请求之间保持cookie。

Session对象具有主要的RequestsAPI的所有方法。

  1. s=requests.Session()
  2. s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
  3. r=s.get('http://httpbin.org/cookies')
  4. print(r.text)
  1. {
  2. "cookies": {
  3. "sessioncookie": "123456789"
  4. }
  5. }
  1. #会话也可用来为请求方法提供缺省数据
  2. s=request.Session()
  3. s.auth=('user','pass')
  4. s.headers.update({'x-test':'true'})
  5. #x-test和x-test2都会发送出去
  6. s.get('http://httpbin.org/headers',headers={'x-test2':'true'})
  1. #任何传递给请求方法的字典都会与已设置会话层数据合并。但是方法级别的参数不会被跨请求保持,比如:
  2. s=requests.Session()
  3. r=s.get('http://httpbin.org/cookies',cookies={'from-my':'browser'})
  4. print(r.text)
  1. {
  2. "cookies": {
  3. "from-my": "browser"
  4. }
  5. }
  1. r=s.get('http://httpbin.org/cookies')
  2. print(r.text)
  1. {
  2. "cookies": {}
  3. }

请求与响应对象

其实requests.get()调用,第一是构建一个Request对象,向某个服务器发送请求,第二是从服务器返回的响应Response对象,该对象包含服务器返回的所有信息。

  1. r.headers#访问服务器返回来的响应头部信息
  2. r.request.headers#获取发送到服务器的请求的头部信息

准备的请求

如果在发送请求之前,需要对body或者header进行额外处理,可以这么做:

  1. from requests import Request,Session
  2. s=Session()
  3. req=Request('GET',url,data=data,headers=header)
  4. prepped=req.prepare()
  5. #对prepped的body和header进行修改
  6. resp=s.send(prepped,stream=stream,verify=verify,proxies=proxies,cert=cert,timeout=timeout)
  7. print(resp.status_code)

但是上述代码会失去Requests Session对象的一些优势,尤其是Session级别的状态,要获取一个带有状态的PreparedRequest,需要用Session.prepare_request()取代Request.prepare()的调用。

SSL证书验证

SSL验证默认开始,如果验证失败,会抛出SSLError

  1. requests.get('http://requestb.in')
  1. <Response [200]>
  1. requests.get('https://github.com',verify=True)
  2. #如果设置为False,会忽略对SSL证书的验证。
  1. <Response [200]>

verify可以是包含可信任CA证书的文件夹路径:比如verify='/path/to/certfile'。

或者将verify保持在会话中:

  1. s = requests.Session()
  2. s.verify = '/path/to/certfile'

代理-proxies参数

  1. import requests
  2. proxies = {
  3. "http": "http://10.10.1.10:3128",
  4. "https": "http://10.10.1.10:1080",
  5. }
  6. requests.get("http://example.org", proxies=proxies)

如果您觉得感兴趣的话,可以添加我的微信公众号:一步一步学Python

爬虫入门【2】Requests库简介的更多相关文章

  1. 网络爬虫入门:你的第一个爬虫项目(requests库)

    0.采用requests库 虽然urllib库应用也很广泛,而且作为Python自带的库无需安装,但是大部分的现在python爬虫都应用requests库来处理复杂的http请求.requests库语 ...

  2. 爬虫入门之urllib库详解(二)

    爬虫入门之urllib库详解(二) 1 urllib模块 urllib模块是一个运用于URL的包 urllib.request用于访问和读取URLS urllib.error包括了所有urllib.r ...

  3. Python爬虫入门——使用requests爬取python岗位招聘数据

    爬虫目的 使用requests库和BeautifulSoup4库来爬取拉勾网Python相关岗位数据 爬虫工具 使用Requests库发送http请求,然后用BeautifulSoup库解析HTML文 ...

  4. 从0开始学爬虫9之requests库的学习之环境搭建

    从0开始学爬虫9之requests库的学习之环境搭建 Requests库的环境搭建 环境:python2.7.9版本 参考文档:http://2.python-requests.org/zh_CN/l ...

  5. 芝麻HTTP: Python爬虫利器之Requests库的用法

    前言 之前我们用了 urllib 库,这个作为入门的工具还是不错的,对了解一些爬虫的基本理念,掌握爬虫爬取的流程有所帮助.入门之后,我们就需要学习一些更加高级的内容和工具来方便我们的爬取.那么这一节来 ...

  6. Python爬虫入门之Urllib库的高级用法

    1.设置Headers 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Headers 的属性. 首先,打开我们的浏览 ...

  7. Python爬虫入门之Urllib库的基本使用

    那么接下来,小伙伴们就一起和我真正迈向我们的爬虫之路吧. 1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解 ...

  8. python爬虫之一:requests库

    目录 安装requtests requests库的连接异常 HTTP协议 HTTP协议对资源的操作 requests库的7个主要方法 request方法 get方法 网络爬虫引发的问题 robots协 ...

  9. PYTHON 爬虫笔记三:Requests库的基本使用

    知识点一:Requests的详解及其基本使用方法 什么是requests库 Requests库是用Python编写的,基于urllib,采用Apache2 Licensed开源协议的HTTP库,相比u ...

随机推荐

  1. javaweb项目自定义错误页面

    当我们把一个web项目成功发布出去,但是有些页面还有待完善的时候,会出现404错误页面.这个会给用户很差的体验.如何将这些错误页面修改为自定义的错误页界面,给用户一些友好的提示呢? 首先我们在web. ...

  2. Node.js 网页瘸腿稍强点爬虫再体验

    这回爬虫走得好点了,每次正常读取文章数目总是一样的,但是有程序僵住了情况,不知什么原因. 代码如下: // 内置http模块,提供了http服务器和客户端功能 var http=require(&qu ...

  3. OpenCV2学习笔记(十五):利用Cmake高速查找OpenCV函数源代码

    在使用OpenCV时,在对一个函数的调用不是非常了解的情况下,通常希望查到该函数的官方声明.而假设想进一步研究OpenCV的函数,则必须深入到源码. 在VS中我们能够选中想要查看的OpenCV函数,点 ...

  4. JAVA Eclipse如何开发Android的多页面程序

    Fragment可以认为是Activity的一个界面的组成部分,Fragment必须依存于Activity.   在layout文件夹中新建一个xml文件,布局方式采用RelativeLayout,注 ...

  5. std::multimap 按照key遍历---

    #include <iostream> #include <unordered_map> using namespace std; int main() { unordered ...

  6. WAMP设置

    当安装好WAMP后,windows右下角会出现WAMP Server的图标,如图所示! 当中集成了PHP开发的常用功能. Localhost:表示启动浏览器打开本地首页 My Projects:项目文 ...

  7. 【SpringMVC学习09】SpringMVC与前台的json数据交互

    json数据格式在接口调用中.html页面中比较常用,json格式比较简单,解析也比较方便,所以使用很普遍.在springmvc中,也支持对json数据的解析和转换,这篇文章主要总结一下springm ...

  8. 解决Linux上解压jdk报错gzip: stdin: not in gzip format

    最近在阿里上买了个服务器玩,需要安装jdk,在解压过程中遇到了一些问题,又是一番Google度娘,终于解决了.问题原因让我有点无奈…… 输入 #tar -xvf jdk-8u131-linux-x64 ...

  9. Android中多线程编程(三)Handler更新UI的方式

    Handler更新UI的方式和原因以及遇到的问题 1.方式: 仅仅能通过Handler来更新UI. 代码例如以下: package com.chengdong.su.handlerdemo; impo ...

  10. vmstat 命令

    vmstat是Virtual Meomory Statistics(虚拟内存统计)的缩写,可对操作系统的虚拟内存.进程.CPU活动进行监控.他是对系统的整体情况进行统计,不足之处是无法对某个进程进行深 ...