Requests库的使用



  • 基于urllib3改写的,API更加方便, 简单易用
  • 几句代码实现代理、cookie... 设置
请求方式
requests.post('http://httpbin.org/post')
requests.delete('http://httpbin.org/delete')
requests.put('http://httpbin.org/put')
requests.header('http://httpbin.org/get')
requests.options('http://httpbin.org/get')
解析json
import requests
response = requests.get('http://httpbin.org/get')
print(type(response))
print(response.json())
# response.json() 等同于: json.loads(response.text)
print(type(response.json()))

输出

<class 'requests.models.Response'>
{'url': 'http://httpbin.org/get', 'origin': '111.206.170.62', 'args': {}, 'headers': {'Accept': '*/*', 'Connection': 'close', 'Accept-Encoding': 'gzip, deflate', 'User-Agent': 'python-requests/2.18.4', 'Host': 'httpbin.org'}}
<class 'dict'>
获取二进制数据

获取图片二进制数据,保存到本地。

response = requests.get('https://b-ssl.duitang.com/uploads/item/201707/02/20170702174136_waZHh.thumb.700_0.jpeg')
with open('touxiang.jpg', 'wb') as f:
    f.write(response.content)
    f.close()
添加headers

访问知乎:

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3159.5 Mobile Safari/537.36'
}
response = requests.get('http://www.zhihu.com/explore', headers=headers)
print(response.text)

基于post请求

import requests

data = {
    'name': 'dimples',
    'age': '23',
}
response = requests.post('http://httpbin.org/post', data=data)
print(response.text)

response

文件上传
import requests
files = {'files': open('touxiang.jpg', 'rb')}
response = requests.post('http://httpbin.org/post', files=files)
print(response.text)
获取cookie
response = requests.get('http://www.baidu.com')
print(response.cookies)
for key, value in response.cookies.items():
    print(key+"="+value)

输出:

<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
BDORZ=27315
会话保持

模拟登录

requests.get('http://httpbin.org/cookies/set/number/12345')
response = requests.get('http://httpbin.org/cookies')
print(response.text)
{
  "cookies": {}
}

**实现在同一个浏览器set和get: 使用session **

s = requests.Session()
s.get('http://httpbin.org/cookies/set/number/12345')
response = s.get('http://httpbin.org/cookies')
print(response.text)
{
  "cookies": {
    "number": "12345"
  }
}
证书认证
  • verify=False:是否要进行证书的验证,默认True
# 消除警告信息
<!--from requests.packages import urllib3-->
<!--urllib3.disable_warnings()-->

response = requests.get('http://www.12306.cn', verify=False)
print(response.status_code)
认证设置
from requests.auth import HTTPBasicAuth

response = requests.get('http://***', auth=HTTPBasicAuth('user', '123'))
print(response.status_code)

或者:

response = requests.get('http://120.27.34.24:9001', auth=('user', '123'))
print(response.status_code)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值