转自:http://my.oschina.net/yangyanxing/blog/280029

早就听说requests的库的强大,只是还没有接触,今天接触了一下,发现以前使用urllib,urllib2等方法真是太搓了……

这里写些简单的使用初步作为一个记录

一、安装 http://cn.python-requests.org/en/latest/user/install.html#install

二、发送无参数的get请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> r = requests.get('http://httpbin.org/get')
>>> print r.text
{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "close",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.3.0 CPython/2.6.6 Windows/7",
    "X-Request-Id": "8a28bbea-55cd-460b-bda3-f3427d66b700"
  },
  "origin": "124.192.129.84",
}

三、发送带参数的get请求,将key与value放入一个字典中,通过params参数来传递,其作用相当于urllib.urlencode

1
2
3
4
5
>>> import requests
>>> pqyload = {'q':'杨彦星'}
>>> r = requests.get('http://www.so.com/s',params = pqyload)
>>> r.url

四、发送post请求,通过data参数来传递,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
>>> payload = {'a':'杨','b':'hello'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print r.text
{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "a": "\u6768",
    "b": "hello"
  },
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "close",
    "Content-Length": "19",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.3.0 CPython/2.6.6 Windows/7",
    "X-Request-Id": "c81cb937-04b8-4a2d-ba32-04b5c0b3ba98"
  },
  "json": null,
  "origin": "124.192.129.84",
}
>>>

可以看到,post参数已经传到了form里,data不光可以接受字典类型的数据,还可以接受json等格式

1
2
3
>>> payload = {'a':'杨','b':'hello'}
>>> import json
>>> r = requests.post('http://httpbin.org/post', data=json.dumps(payload))

五、发送文件的post类型,这个相当于向网站上传一张图片,文档等操作,这时要使用files参数

1
2
3
>>> files = {'file': open('touxiang.png', 'rb')}
>>> r = requests.post(url, files=files)

5.1 定制headers,使用headers参数来传递

1
2
3
4
5
6
>>> import json
>>> payload = {'some': 'data'}
>>> headers = {'content-type': 'application/json'}
 
>>> r = requests.post(url, data=json.dumps(payload), headers=headers)

六、响应内容

6.1 响应状态码

r = requests.get('http://httpbin.org/get')
print r.status_code
6.2 响应头
1
2
>>> print r.headers
{'content-length': '519', 'server': 'gunicorn/18.0', 'connection': 'keep-alive', 'date': 'Sun, 15 Jun 2014 14:19:52 GMT', 'access-control-allow-origin': '*', 'content-type': 'application/json'}

也可以取到这个个别的响应头用来做一些判断,这里的参数是不区分大小写的

r.headers[‘Content-Type’]

r.headers.get(‘Content-Type’)

6.3 响应内容,前面已经在应用了

r.text

r.content

七、获取响应中的cookies

1
2
3
>>> r = requests.get('http://www.baidu.com')
>>> r.cookies['BAIDUID']
'D5810267346AEFB0F25CB0D6D0E043E6:FG=1'

也可以自已定义请求的COOKIES

1
2
3
4
5
6
7
8
9
10
11
>>> cookies = {'cookies_are':'working'}
>>> r = requests.get(url,cookies = cookies)
>>>
>>> print r.text
{
  "cookies": {
    "cookies_are": "working"
  }
}
>>>

cookies还有很多,因为目前我也还不是很多,以后再扩充吧

八、使用timeout参数设置超时时间

>>> requests.get('http://github.com', timeout=1) 
<Response [200]>

如果将时间设置成非常小的数,如requests.get('http://github.com', timeout=0.001),那么如果在timeout的时间内没有连接,那么将会抛出一个Timeout的异常

九、访问中使用session

先初始化一个session对象,s = requests.Session() 
然后使用这个session对象来进行访问,r = s.post(url,data = user)

参考文章 http://blog.csdn.net/iloveyin/article/details/21444613 基本上都是从这扒的代码

以下通过访问人人网来获取首页中的最近来访问,然后再访问查看更多的来访来读取更多的最近来访

更多的来访就是以带session的访问http://www.renren.com/myfoot.do

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#coding:utf-8
import requests
import re
 
 
user = {'email':'email','password':'pass'}
s = requests.Session()
r = s.post(url,data = user)
 
html = r.text
visit = []
first = re.compile(r'</span><span class="time-tip first-tip"><span class="tip-content">(.*?)</span>')
second = re.compile(r'</span><span class="time-tip"><span class="tip-content">(.*?)</span>')
third = re.compile(r'</span><span class="time-tip last-second-tip"><span class="tip-content">(.*?)</span>')
last = re.compile(r'</span><span class="time-tip last-tip"><span class="tip-content">(.*?)</span>')
visit.extend(first.findall(html))
visit.extend(second.findall(html))
visit.extend(third.findall(html))
visit.extend(last.findall(html))
for i in visit:
    print i
 
print '以下是更多的最近来访'
fm = re.compile(r'"name":"(.*?)"')
visitmore = fm.findall(vm.text)
for i in visitmore:
    print i

python的requests初步使用的更多相关文章

  1. Python爬虫之使用Fiddler+Postman+Python的requests模块爬取各国国旗

    介绍   本篇博客将会介绍一个Python爬虫,用来爬取各个国家的国旗,主要的目标是为了展示如何在Python的requests模块中使用POST方法来爬取网页内容.   为了知道POST方法所需要传 ...

  2. Python——安装requests第三方库

    使用pip安装 在cmd下cd到这个目录下C:\Python27\Scripts,然后执行pip install requests 在cmd 命令行执行 E:   进入e盘 cd  Python\pr ...

  3. 关于Python ,requests的小技巧

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/xie_0723/article/details/52790786 关于 Python Request ...

  4. Python之Requests的高级用法

    # 高级用法 本篇文档涵盖了Requests的一些更加高级的特性. ## 会话对象 会话对象让你能够跨请求保持某些参数.它也会在同一个Session实例发出的所有请求之间保持cookies. 会话对象 ...

  5. python的requests快速上手、高级用法和身份认证

    https://blog.csdn.net/qq_25134989/article/details/78800209 快速上手 迫不及待了吗?本页内容为如何入门 Requests 提供了很好的指引.其 ...

  6. Python 安装requests和MySQLdb

    Python 安装requests和MySQLdb 2017年10月02日 0.系统版本 0.1 查看系统版本 [root@localhost ~]# uname -a Linux localhost ...

  7. 【转】使用Python的Requests库进行web接口测试

    原文地址:使用Python的Requests库进行web接口测试 1.Requests简介 Requests 是使用 Apache2 Licensed 许可证的 HTTP 库.用 Python 编写, ...

  8. 转来的——python webdriver自动化测试初步印象——转来的

    python webdriver自动化测试初步印象 以下示例演示启动firefox,浏览google.com,搜索Cheese,等待搜索结果,然后打印出搜索结果页的标题 from selenium i ...

  9. Python+Unittest+Requests+PyMysql+HTMLReport 接口自动化框架

    整体框架使用的是:Python+Unittest+Requests+PyMysql+HTMLReport  多线程并发模式 主要依赖模块 Unittest.Requests.PyMysql.HTMLR ...

随机推荐

  1. POJ 3620 Avoid The Lakes【DFS找联通块】

    Avoid The Lakes Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 6826   Accepted: 3637 D ...

  2. Codeforces 581F Zublicanes and Mumocrates(树型DP)

    题目链接  Round 322 Problem F 题意  给定一棵树,保证叶子结点个数为$2$(也就是度数为$1$的结点),现在要把所有的点染色(黑或白) 要求一半叶子结点的颜色为白,一半叶子结点的 ...

  3. springMVC笔记:@ResponseBody

    使用@ResponseBody的方式,将Map形返回值转为json,用作POST请求的返回值.为了解决406 Not Acceptable错误,需要检查以下几项: 1. 依赖包中包含jackson-m ...

  4. 线段树【p1115】 最大子段和

    题目描述-->p1115 最大子段和 虽然是一个普及-的题,但我敲了线段树 qwq 数组定义 \(lsum[ ]\)代表 该区间左端点开始的最大连续和. \(rsum[ ]\)代表 该区间右端点 ...

  5. Linux/Unix面试题

    shell中如何改变文件中的某个关键字 unix命令 unix shell中在特定文件夹内查找包含指定字符串的文件用哪个命令 如何用要shell找到指定目录下的最近一天更新的文件,要包含子目录 Lin ...

  6. Apache2 httpd.conf 配置详解

    Apache2 httpd.conf 配置详解 <第一部分> 常用配置指令说明 1. ServerRoot:服务器的基础目录,一般来说它将包含conf/和logs/子目录,其它配置文件的相 ...

  7. 详细解析ASP.NET中Request接收参数乱码原理

    起因:今天早上被同事问了一个问题:说接收到的参数是乱码,让我帮着解决一下. 实际情景: 同事负责的平台是Ext.js框架搭建的,web.config配置文件里配置了全局为“GB2312”编码: < ...

  8. 写给嵌入式程序员的循环冗余校验(CRC)算法入门引导

    写给嵌入式程序员的循环冗余校验(CRC)算法入门引导 http://blog.csdn.net/liyuanbhu/article/details/7882789 前言 CRC校验(循环冗余校验)是数 ...

  9. jmeter 部署问题。

    -D  systemproperty 1.双网卡机器设置 执行 jmeter-server  -Djava.rmi.server.hostname=189.61.143.199 2.在Beanshel ...

  10. C#中out与ref区别

    一.ref(参考)与out区别 1.out(只出不进) 将方法中的参数传递出去,在方法中将该参数传递出去之前需要在该方法起始赋初值:在方法外传递的该参数可以不用赋值: 简单理解就是:将一个东西抛出去之 ...