Requests 是使用 Apache2 Licensed 许可证的 HTTP 库。用 Python 编写,真正的为人类着想。

Python 标准库中的 urllib2 模块提供了你所需要的大多数 HTTP 功能,但是它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。

在Python的世界里,事情不应该这么麻烦。

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

(以上转自Requests官方文档)

2、Requests模块安装

点此下载

然后执行安装

1
$ python setup.py install

个人推荐使用pip安装

1
pip install requests

也可以使用easy_install安装

1
easy_install requests

尝试在IDE中import requests,如果没有报错,那么安装成功。

3、Requests模块简单入门

#HTTP请求类型
#get类型
r = requests.get('https://github.com/timeline.json')
#post类型
r = requests.post("http://m.ctrip.com/post")
#put类型
r = requests.put("http://m.ctrip.com/put")
#delete类型
r = requests.delete("http://m.ctrip.com/delete")
#head类型
r = requests.head("http://m.ctrip.com/head")
#options类型
r = requests.options("http://m.ctrip.com/get") #获取响应内容
print r.content #以字节的方式去显示,中文显示为字符
print r.text #以文本的方式去显示 #URL传递参数
payload = {'keyword': '日本', 'salecityid': '2'}
r = requests.get("http://m.ctrip.com/webapp/tourvisa/visa_list", params=payload)
print r.url #示例为http://m.ctrip.com/webapp/tourvisa/visa_list?salecityid=2&keyword=日本 #获取/修改网页编码
r = requests.get('https://github.com/timeline.json')
print r.encoding
r.encoding = 'utf-8' #json处理
r = requests.get('https://github.com/timeline.json')
print r.json() #需要先import json #定制请求头
url = 'http://m.ctrip.com'
headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'}
r = requests.post(url, headers=headers)
print r.request.headers #复杂post请求
url = 'http://m.ctrip.com'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload)) #如果传递的payload是string而不是dict,需要先调用dumps方法格式化一下 #post多部分编码文件
url = 'http://m.ctrip.com'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files) #响应状态码
r = requests.get('http://m.ctrip.com')
print r.status_code #响应头
r = requests.get('http://m.ctrip.com')
print r.headers
print r.headers['Content-Type']
print r.headers.get('content-type') #访问响应头部分内容的两种方式 #Cookies
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies['example_cookie_name'] #读取cookies url = 'http://m.ctrip.com/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies) #发送cookies #设置超时时间
r = requests.get('http://m.ctrip.com', timeout=0.001) #设置访问代理
proxies = {
"http": "http://10.10.10.10:8888",
"https": "http://10.10.10.100:4444",
}
r = requests.get('http://m.ctrip.com', proxies=proxies)

4、Requests示例

json请求

 1 #!/user/bin/env python
2 #coding=utf-8
3 import requests
4 import json
5
6 class url_request():
7 def __init__(self):
8 """ init """
9
10 if __name__=='__main__':
11 headers = {'Content-Type' : 'application/json'}
12 payload = {'CountryName':'中国',
13 'ProvinceName':'陕西省',
14 'L1CityName':'汉中',
15 'L2CityName':'城固',
16 'TownName':'',
17 'Longitude':'107.33393',
18 'Latitude':'33.157131',
19 'Language':'CN'
20 }
21 r = requests.post("http://www.xxxxxx.com/CityLocation/json/LBSLocateCity",headers=headers,data=payload)
22 #r.encoding = 'utf-8'
23 data=r.json()
24 if r.status_code!=200:
25 print "LBSLocateCity API Error " + str(r.status_code)
26 print data['CityEntities'][0]['CityID'] #打印返回json中的某个key的value
27 print data['ResponseStatus']['Ack']
28 print json.dumps(data,indent=4,sort_keys=True,ensure_ascii=False) #树形打印json,ensure_ascii必须设为False否则中文会显示为unicode

xml请求

#!/user/bin/env python
#coding=utf-8
import requests class url_request():
def __init__(self):
""" init """ if __name__=='__main__': headers = {'Content-type': 'text/xml'}
XML = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><Request xmlns="http://tempuri.org/"><jme><JobClassFullName>WeChatJSTicket.JobWS.Job.JobRefreshTicket,WeChatJSTicket.JobWS</JobClassFullName><Action>RUN</Action><Param>1</Param><HostIP>127.0.0.1</HostIP><JobInfo>1</JobInfo><NeedParallel>false</NeedParallel></jme></Request></soap:Body></soap:Envelope>'
url = 'http://jobws.push.mobile.xxxxxxxx.com/RefreshWeiXInTokenJob/RefreshService.asmx'
r = requests.post(url,headers=headers,data=XML)
#r.encoding = 'utf-8'
data = r.text
print data

5、参考文档

http://cn.python-requests.org/en/latest/

http://docs.python-requests.org/en/latest/user/quickstart.html

爬虫初窥day4:requests的更多相关文章

  1. 爬虫初窥day3:BeautifulSoup

    信息提取 1.通过Tag对象的属性和方法 #!/usr/bin/python # -*- coding: utf- -*- from urllib.request import urlopen fro ...

  2. 爬虫初窥day2:正则

    正则在线测试 http://tool.oschina.net/regex https://www.regexpal.com/ http://tool.chinaz.com/regex exp1:筛选所 ...

  3. 爬虫初窥day1:urllib

    模拟“豆瓣”网站的用户登录 # coding:utf-8 import urllib url = 'https://www.douban.com/' data = urllib.parse.urlen ...

  4. python爬虫 scrapy2_初窥Scrapy

    sklearn实战-乳腺癌细胞数据挖掘 https://study.163.com/course/introduction.htm?courseId=1005269003&utm_campai ...

  5. Scrapy 1.4 文档 01 初窥 Scrapy

    初窥 Scrapy Scrapy 是用于抓取网站并提取结构化数据的应用程序框架,其应用非常广泛,如数据挖掘,信息处理或历史存档. 尽管 Scrapy 最初设计用于网络数据采集(web scraping ...

  6. Scrapy001-框架初窥

    Scrapy001-框架初窥 @(Spider)[POSTS] 1.Scrapy简介 Scrapy是一个应用于抓取.提取.处理.存储等网站数据的框架(类似Django). 应用: 数据挖掘 信息处理 ...

  7. scrapy2_初窥Scrapy

    递归知识:oop,xpath,jsp,items,pipline等专业网络知识,初级水平并不是很scrapy,可以从简单模块自己写. 初窥Scrapy Scrapy是一个为了爬取网站数据,提取结构性数 ...

  8. python2.7 爬虫初体验爬取新浪国内新闻_20161130

    python2.7 爬虫初学习 模块:BeautifulSoup requests 1.获取新浪国内新闻标题 2.获取新闻url 3.还没想好,想法是把第2步的url 获取到下载网页源代码 再去分析源 ...

  9. python爬虫学习(6) —— 神器 Requests

    Requests 是使用 Apache2 Licensed 许可证的 HTTP 库.用 Python 编写,真正的为人类着想. Python 标准库中的 urllib2 模块提供了你所需要的大多数 H ...

随机推荐

  1. BOM 表

    ';--查看BOM创建日期时间 SELECT * FROM SAPSR3.ZSTPO_OUT2011_1@SAP_SEP; SELECT * FROM SAPSR3.ZSTPO_OUT2012_1@S ...

  2. JavaScript中判断null、undefined与NaN的方法

    1.判断undefined: ? 1 2 3 4 var tmp = undefined; if (typeof(tmp) == "undefined"){ alert(" ...

  3. MySql安装和基本管理&mysql语句

    MySql安装和基本管理   本章内容: mysql的安装.启动 mysql破解密码 统一字符编码 MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于 Oracle 旗下 ...

  4. zabbix 短信报警

    使用的短信平台是云片网,接口请看官网短信接口API文档,有示例 进入server服务器存放脚本的文件夹,默认路径是 [root@test zabbix]# cat zabbix_server.conf ...

  5. vue-router导航守卫,限制页面访问权限

    在项目开发过程中,经常会需要登录.注册.忘记密码等,也有很多页面是需要登录后才能访问,有些页面是无需登录就可以访问的,那么vue是怎么来限制这些访问权限问题的呢? vue-router导航守卫的bef ...

  6. 二进制中1的个数(python)

    题目描述 输入一个整数,输出该数二进制表示中1的个数.其中负数用补码表示. # -*- coding:utf-8 -*- class Solution: def NumberOf1(self, n): ...

  7. Dbutils 连接数据库

    用了JDBC后接着学习Dbutils连接数据库 1.添加驱动包 Class.forName("oracle.jdbc.driver.OracleDriver"); 2.获取数据库连 ...

  8. TOJ4757: 12345(数学)

    传送门 时间限制(普通/Java):1000MS/3000MS     内存限制:65536KByte 描述 为了说明水题也不是那么好AC的,FD出了一个由数字1~5组成的题目,题意如下: 给定一个正 ...

  9. AngularJS——第5章 作用域

    第5章 作用域 通常AngularJS中应用(App)是由若干个视图(View)组合成而成的,而视图(View)又都是HTML元素,并且HTML元素是可以互相嵌套的,另一方面视图都隶属于某个控制器(C ...

  10. python调试工具pdb

    pdb是基于命令行的调试工具,非常类似gnu的gdb(调试c/c++). 命令 简写命令 作用 break b 设置断点 continue c 继续执行程序 list l 查看当前行的代码段 step ...