Python-Requests
Posted xuwei1
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python-Requests相关的知识,希望对你有一定的参考价值。
一、发送请求
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的主要内容,如果未能解决你的问题,请参考以下文章