Python3.x:requests的用法

Posted 整合侠

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python3.x:requests的用法相关的知识,希望对你有一定的参考价值。

Python3.x:requests的用法

1,requests 比 urllib.request 容错能力更强;

2,通常用法:

(1).认证、状态码、header、编码、json

r = requests.get(https://api.github.com/user, auth=(user, pass))
r.status_code

r.headers[content-type]
输出:application/json; charset=utf8
r.encoding
输出:utf-8
r.text
输出:u{"type":"User"...
r.json()
输出:{uprivate_gists: 419, utotal_private_repos: 77, ...}

(2).发起请求

import requests
URL="http://www.bsdmap.com/"
#
r = requests.get(URL)
#
r = requests.post(URL)
#
r = requests.put(URL)
#
r = requests.delete(URL)
#
r = requests.head(URL)
#
r = requests.options(URL)

(3).通过URL传递参数

payload = {key1: value1, key2: value2}
r = requests.get("http://httpbin.org/get", params=payload)
print r.url
输出:uhttp://httpbin.org/get?key2=value2&key1=value1

(4).返回内容

import requests
r = requests.get(https://github.com/timeline.json)
r.text
输出:[{"repository":{"open_issues":0,"url":"https://github.com/...
r.encoding
输出:utf-8
r.encoding = ISO-8859-1

(5).二进制内容

r.content
输出:b[{"repository":{"open_issues":0,"url":"https://github.com/...

from PIL import Image
from StringIO import StringIO
i = Image.open(StringIO(r.content))

(6).JSON

import requests
r = requests.get(https://github.com/timeline.json)
r.json()
输出:[{urepository: {uopen_issues: 0, uurl: https://github.com/...

(7).超时

requests.get(http://github.com, timeout=0.001)

(8).自定义header

import json
url = https://api.github.com/some/endpoint
payload = {some: data}
headers = {content-type: application/json}

r = requests.post(url, data=json.dumps(payload), headers=headers)

官方文档:http://docs.python-requests.org/en/latest/user/quickstart/

 

以上是关于Python3.x:requests的用法的主要内容,如果未能解决你的问题,请参考以下文章

python3.x 和 python2.x关于 urllib的用法

python3.4 + requests + re 仿写糗事百科爬虫,遇到一个疑惑,求助

C#-WebForm-★内置对象简介★Request-获取请求对象Response相应请求对象Session全局变量(私有)Cookie全局变量(私有)Application全局公共变量Vi(代码片段

Python3中urllib使用与源代码

python3.x requests 模块使用

python2.x到python3.x函数变化