码迷,mamicode.com
首页 > 编程语言 > 详细

Python-Requests

时间:2019-06-22 17:00:40      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:github   定向   latest   跨域   list   它的   tps   oss   完整   

一、发送请求

import requests
r = requests.get('https://api.github.com/events')
r = requests.post('http://httpbin.org/post', data = {'key':'value'})

二、URL传参

2.1:普通参数

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

2.2:一键多值

url = 'http://httpbin.org/get'
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get(url=url, params=payload)
print(r.url)
# http://httpbin.org/get?key1=value1&key2=value2&key2=value3

三、响应内容

3.1:unicode 字符

import requests
r = requests.get('https://api.github.com/events')
print(r.text)    # 获取响应内容
print(r.encoding)   # 'utf-8'

3.2:二进制响应内容,获取照片

import requests
url = 'https://b-ssl.duitang.com/uploads/item/201504/29/20150429075539_cy8vV.jpeg'
r = requests.get(url)
path = 'img/1.jpg'
with open(path, 'wb') as f:
    """写入一张照片"""
    f.write(r.content)

3.3:JSON 响应内容

JSON 解码器

import requests
r = requests.get('https://api.github.com/events')
print(r.json())
print(r.text)

3.4:响应状态码

r = requests.get('http://httpbin.org/get')
print(r.status_code)    #200
print(r.status_code == requests.codes.ok)   # True

3.5:响应头

r = requests.get('http://httpbin.org/get')
print(r.headers)
print(r.headers['Content-Type'])

四、定制请求

4.1:定制请求头

url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)

4.2:POST 请求

url = "http://httpbin.org/post"
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post(url, data=payload)
print(r.text)

4.3:一参多值POST

你还可以为 data 参数传入一个元组列表。在表单中多个元素使用同一 key 的时候,这种方式尤其有效:

url = "http://httpbin.org/post"
payload = (('key1', 'value1'), ('key1', 'value2'))
r = requests.post(url, data=payload)
print(r.text)

4.4:str 转字典发送

import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))
r = requests.post(url, json=payload)
print(r.text)

五、上传文件

5.1:上传一个xls

url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
print(r.text)

5.2:显式地设置文件名,文件类型和请求头

url = 'http://httpbin.org/post'
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)
print(r.text)

5.3:发送作为文件来接收的字符串

url = 'http://httpbin.org/post'
files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
r = requests.post(url, files=files)
print(r.text)

六、Cookie

6.1:访问Cookie

url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
data = r.cookies['example_cookie_name']
print(data)
print(r.cookies['example_cookie_name'])

6.2:发送cookies到服务器

url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)
print(r.text)

6.3:传Cookie Jar到Requests 中

Cookie 的返回对象为 RequestsCookieJar,它的行为和字典类似,但接口更为完整,适合跨域名跨路径使用。你还可以把 Cookie Jar 传到 Requests 中:

jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
url = 'http://httpbin.org/cookies'
r = requests.get(url, cookies=jar)
print(r.text)

七、超时

r = requests.get('https://github.com', timeout=2)
print(r.text)

八、重定向与请求历史

Github 将所有的 HTTP 请求重定向到 HTTPS:

r = requests.get('http://github.com')
print(r.url)
print(r.status_code)
print(r.history)

九、错误与异常

  • 遇到网络问题(如:DNS 查询失败、拒绝连接等)时,Requests 会抛出一个 ConnectionError 异常。
  • 如果 HTTP 请求返回了不成功的状态码, Response.raise_for_status() 会抛出一个 HTTPError 异常。
  • 若请求超时,则抛出一个 Timeout 异常。
  • 若请求超过了设定的最大重定向次数,则会抛出一个 TooManyRedirects 异常。
  • 所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException 。

参考Requests快速上手

Python-Requests

标签:github   定向   latest   跨域   list   它的   tps   oss   完整   

原文地址:https://www.cnblogs.com/xuwei1/p/11069483.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!