requests模块

模块简介

requests模块主要用于发起网路请求,如请求payload或者爬虫所用,返回一个respond对象。

常用方法

一、发送请求

1、请求方式

1.发送get请求
方式一:直接请求
>>> r = requests.get('https://api.github.com/events')
方式二:携带get参数
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get("http://httpbin.org/get", params=payload)
2.发送post请求
方式一:
>>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})
方式二:payload利用的是字典,适用于不同键值对
>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
方式三:payload利用的是元组,适用于表单中多个元素使用同一 key 的时候
>>> payload = (('key1', 'value1'), ('key1', 'value2'))
>>> r = requests.post('http://httpbin.org/post', data=payload)
方式四:json格式请求
>>> payload = {'some': 'data'}
>>> r = requests.post(url, json=payload)
方式五:发送文件
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)

2、定制请求头 

方式一:直接携带headers内容
>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)

3、其他参数

timeout     设置超时
>>> r = requests.get('https://github.com/', timeout=0.001)
cookies     携带cookie
cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)
verify       是否请求ssl证书验证,false代表请求不去验证ssl证书,默认为true即为验证,也可以指定证书地址
>>> r = requests.get(url, verify=false)
>>> r = requests.get(url, verify='/path/to/certfile')
allow_redirects     重定向处理,flase代表请求不进行重定向,默认为true即所有请求都重定向
>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]
cert         客户端证书
>>> requests.get('https://kennethreitz.org', cert=('/path/client.crt', '/path/client.key'))
<Response [200]>
proxies       代理
>>> proxies = {
        "http": "10.10.10.10:3128",
        "https": "user:password@10.10.10.10:3128/",
        "http": "socks5://user:password@host:port/"              # 需要条件安装socks库 pip3 install 'requests[socks]',需要密码的时候结尾可能需要加个/
    }
>>> requests.get('https://kennethreitz.org', proxies=)
>>> requests.get('https://www.test.com',proxies=proxies,verify=False)   //如果需要抓取https需要关闭证书验证
auth           身份认证
>>> requests.get('http://localhost:8080', auth=('username', 'password'))

二、响应

1、响应格式

1.text     响应内容
Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。
>> r.text
u'[{"repository":{"open_issues":0,"url":"https://github.com/...
2.encoding     更改响应编码
>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'
3.content     二进制相应内容
>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...
比如保存请求到的图片保存,因为图片为二进制,直接打印是str类型,是会乱码的。音乐和视频同样的方式请求。
r = request.get("https://github.com/favicon.ico")
with open('favicon.ico','wb') as f:
    f.write(r.content)
更改响应编码
>>> r.content.decode() 默认utf-8
>>> r.content.decode("GBK")
4.JSON     json响应
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

2、响应结果

1.status_code     获取响应码
>>> r.status_code
200
requests内置的状态码查询对象 requests.codes
比如:requests.codes.ok         代表状态码为200
requests.codes.found      代表状态码为302
requests.codes.not_found  代表状态码为404
2.headers     获取响应头
>>> r.headers
{    
    'content-encoding': 'gzip',    
    'transfer-encoding': 'chunked',  
    'connection': 'close',    
    'server': 'nginx/1.0.4',    
    'x-runtime': '148ms',    
    'etag': '"e1ca502697e5c9317743dc078f67693f"',   
    'content-type': 'application/json'
}
3.request.headers     请求头
>>> r.request.headers
{'Accept-Encoding': 'identity, deflate, compress, gzip','Accept': '*/*', 'User-Agent': 'python-requests/0.13.1'}
4.cookie值      获取响应中cookie值
>>> r.cookies['example_cookie_name']
5.request._cookies    获取请求头中的cookie值
>>> r.request._cookies
6.history    这个对象列表按照从最老到最近的请求进行排序。
>>> r = requests.get('http://github.com')
>>> r.url
'https://github.com/'
>>> r.history
[<Response [301]>]

三、会话对象

1.创建会话,跨请求保持一些 cookie
# 保持会话
# 新建一个session对象
sess = requests.session()
# 先完成登录
sess.post('maybe a login url', data=data, headers=headers)
# 然后再在这个会话下去访问其他的网址
sess.get('other urls')
2.提供缺省数据
s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})
# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Thunderclap_

点赞、关注加收藏~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值