您的位置:首页 > 理论基础 > 计算机网络

python爬虫 - python requests网络请求简洁之道

2015-08-29 12:04 369 查看
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, ...}


皮皮Blog

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'
皮皮Blog


[urllib2 vs requests]

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/..."}

皮皮Blog

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
皮皮Blog

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

ref:Requests: HTTP for Humans

requests快速上手

[https://github.com/kennethreitz/requests]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: