python爬虫 - python requests网络请求简洁之道
http://blog.csdn.net/pipisorry/article/details/48086195
requests简介
requests是一个很实用的Python HTTP客户端库,编写爬虫和测试服务器响应数据时经常会用到。大神kennethreitz的作品,简易明了的HTTP请求操作库, 是urllib2的理想替代品。requests is an elegant HTTP library。API简洁明了,这才是Python开发者喜欢的。
requests跟urllib,urllib2类似,但是python的标准库urllib2提供了大部分需要的HTTP功能,但是API太逆天了,一个简单的功能就需要一大堆代码。
Requests 使用的是 urllib3,因此继承了它的所有特性。Requests 支持 HTTP 连接保持和连接池,支持使用 cookie 保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码。现代、国际化、人性化。
requests的功能特性
Requests 完全满足如今网络的需求:
国际化域名和 URLs
Keep-Alive & 连接池
持久的 Cookie 会话
类浏览器式的 SSL 加密认证
基本/摘要式的身份认证
优雅的键/值 Cookies
自动解压
Unicode 编码的响应体
多段文件上传
连接超时
支持 .netrc
适用于 Python 2.6—3.4
线程安全
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> r.headers['content-type']
'application/json; charset=utf8'
>>> r.encoding
'utf-8'
>>> r.text
u'{"type":"User"...'
>>> r.json()
{u'private_gists': 419, u'total_private_repos': 77, ...}
requests和python自带urllib的对比
py2:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib2
gh_url = 'https://api.github.com'
req = urllib2.Request(gh_url)
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, gh_url, 'user', 'pass')
auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)
urllib2.install_opener(opener)
handler = urllib2.urlopen(req)
print handler.getcode()
print handler.headers.getheader('content-type')
# ------
# 200
# 'application/json'
requests
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
r = requests.get('https://api.github.com', auth=('user', 'pass'))
print r.status_code
print r.headers['content-type']
# ------
# 200
# 'application/json'
requests使用举栗
安装
pip install requests
基本使用
>>>import requests
>>> r = requests.get('http://www.****.com') # 发送请求
>>> r.status_code # 返回码 200
>>> r.headers['content-type'] # 返回头部信息'text/html; charset=utf8'
>>> r.encoding # 编码信息'utf-8'
>>> r.text #内容部分(如果存在编码问题,也可以使用r.content,见下面的编码问题部分)
u'<!DOCTYPE html>\n<html xmlns="http://www.***/xhtml"...'...
各种不同HTTP请求
>>> r = requests.post("http://httpbin.org/post")
>>> r = requests.put("http://httpbin.org/put")
>>> r = requests.delete("http://httpbin.org/delete")
>>> r = requests.head("http://httpbin.org/get")
>>> r = requests.options("http://httpbin.org/get")
带参数的请求
>>> payload = {'wd': '张亚楠', 'rn': '100'}
>>> r = requests.get("http://www.baidu.com/s", params=payload)
>>> print r.url
u'http://www.baidu.com/s?rn=100&wd=%E5%BC%A0%E4%BA%9A%E6%A5%A0'
Note: 这里的params可以不用自己进行urlencode的。
获取json结果
>>>r = requests.get('...')
>>>r.json()['data']['country']
'中国'
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
Note: 实际内容:{"message":"Hello there, wayfaring stranger......","documentation_url":"https://developer.github.com/v3/..."}
requests库的编码问题
Request对象在访问服务器后会返回一个Response对象,这个对象将返回的Http响应字节码保存到content属性中。
但是如果你访问另一个属性text时,会返回一个unicode对象,乱码问题就会常常发成在这里。因为Response对象会通过另一个属性encoding来将字节码编码成unicode,而这个encoding属性居然是responses自己猜出来的。
官方文档:
text
Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using chardet.
The encoding of the response content is determined based solely on HTTP headers, following RFC 2616 to the letter. If you can take advantage of non-HTTP knowledge to make a better guess at the encoding, you should set r.encoding appropriately before accessing this property.
所以要么你直接使用content(字节码),要么记得把encoding设置正确。
比如获取一段gbk编码的网页,就需要以下方法才能得到正确的unicode。
import requests url = "http://xxx.xxx.xxx" response = requests.get(url) response.encoding = 'gbk' print response.text
python3 httplib2
不过小编皮皮告诉大家另一种python3的简洁网络请求之道
import httplib2
h = httplib2.Http(".cache")
h.add_credentials('user', 'pass')
r, content = h.request("https://api.github.com", "GET")
print r['status']
print r['content-type']
Note: 也是等同requests的几行代码啊![urllib2 vs requests]
from:http://blog.csdn.net/pipisorry/article/details/48086195
[https://github.com/kennethreitz/requests]
python爬虫 - python requests网络请求简洁之道的更多相关文章
- python网络请求简洁之道--python requests简介
#requests中文文档:http://cn.python-requests.org/en/latest/#学习出处:http://mp.weixin.qq.com/s?__biz=MjM5NzU0 ...
- 使用Python爬虫爬取网络美女图片
代码地址如下:http://www.demodashi.com/demo/13500.html 准备工作 安装python3.6 略 安装requests库(用于请求静态页面) pip install ...
- python爬虫之分析Ajax请求抓取抓取今日头条街拍美图(七)
python爬虫之分析Ajax请求抓取抓取今日头条街拍美图 一.分析网站 1.进入浏览器,搜索今日头条,在搜索栏搜索街拍,然后选择图集这一栏. 2.按F12打开开发者工具,刷新网页,这时网页回弹到综合 ...
- 孤荷凌寒自学python第六十七天初步了解Python爬虫初识requests模块
孤荷凌寒自学python第六十七天初步了解Python爬虫初识requests模块 (完整学习过程屏幕记录视频地址在文末) 从今天起开始正式学习Python的爬虫. 今天已经初步了解了两个主要的模块: ...
- Python爬虫练习(requests模块)
Python爬虫练习(requests模块) 关注公众号"轻松学编程"了解更多. 一.使用正则表达式解析页面和提取数据 1.爬取动态数据(js格式) 爬取http://fund.e ...
- Python爬虫之requests库介绍(一)
一:Requests: 让 HTTP 服务人类 虽然Python的标准库中 urllib2 模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests 自称 ...
- Python爬虫之requests模块(1)
一.引入 Requests 唯一的一个非转基因的 Python HTTP 库,人类可以安全享用. 警告:非专业使用其他 HTTP 库会导致危险的副作用,包括:安全缺陷症.冗余代码症.重新发明轮子症.啃 ...
- python爬虫值requests模块
- 基于如下5点展开requests模块的学习 什么是requests模块 requests模块是python中原生的基于网络请求的模块,其主要作用是用来模拟浏览器发起请求.功能强大,用法简洁高效.在 ...
- Python爬虫 【requests】request for humans
安装 pip install requests 源码 git clone git://github.com/kennethreitz/requests.git 导入 import requests 发 ...
随机推荐
- 防止SpringMVC拦截器拦截js等静态资源文件
SpringMVC提供<mvc:resources>来设置静态资源,但是增加该设置如果采用通配符的方式增加拦截器的话仍然会被拦截器拦截,可采用如下方案进行解决: 方案一.拦截器中增加针对静 ...
- 20160227.CCPP体系详解(0037天)
程序片段(01):01.一对一模式.c+02.中介者模式.c+03.广播模式.c 内容概要:事件 ///01.一对一模式.c #include <stdio.h> #include < ...
- JBOSS EAP实战(2)-集群、NGINX集成、队列与安全
JBOSS HTTP的Thread Group概念 JBOSS是一个企业级的J2EE APP Container,因此它和任何一种成熟的企业级中间件一样具有Thread Group的概念.所谓Thre ...
- Android重绘ListView高度
Android重绘ListView高度 经常会有这样需求,需要ListView默认将所有的条目显示出来,这就需要外层使用ScrollView,ScrollView里面放置一个重绘高度的ListView ...
- How to code like a hacker
We are coding. Are we engineers? Are we programmers? Are we coder? No, I want to be a hacker! Many g ...
- rbac 概念
1 权限管理 1.1 什么是权限管理 分享牛原创,分享牛系列.基本上涉及到用户参与的系统都要进行权限管理,权限管理属于系统安全的范畴,权限管理实现对用户访问系统的控制,按照安全规则或者安全策略控制用户 ...
- git中status指令总是提示内容被修改的解决
大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 最近在用git提交项目修改时发现一个问题,就是多次 git a ...
- Nginx的负载均衡 - 一致性哈希 (Consistent Hash)
Nginx版本:1.9.1 我的博客:http://blog.csdn.net/zhangskd 算法介绍 当后端是缓存服务器时,经常使用一致性哈希算法来进行负载均衡. 使用一致性哈希的好处在于,增减 ...
- Dynamics CRM2016 新功能之从CRM APP中导出数据至EXCEL
新版的CRM对移动端做了很多的改进,这归咎于微软对APP端的越来越重视.自己装了个IOS版的APP,体验了下基本的功能,比原来好用很多很顺滑,这里要介绍的是一个新的数据导出功能. 咱们进入case列表 ...
- SQL 数据库语言分析总结(三)
这次介绍通过mysql-WorkBench这个工具来管理操作数据库. 创建和删除数据库 1.点击创建数据库按钮 2.选中后右键,出现drop schema一项,这个用来删除. 设置默认数据库 选中右键 ...