~request库的使用

官方文档:

安装:pip install request

特点:requests最大的特点就是其风格简单直接优雅。

1.请求方法

import requests        # 导入requests

resp_1 = requests.get('http://httpbin.org/get')    # 发送get请求
resp_2 = requests.post('http://httpbin.org/post', data = {'key':'value'})    # 发送post请求,data:传递参数
resp_3 =requests.put('http://httpbin.org/put',data={'key': 'value'})   #发送put请求,data:传递参数
resp_4 = resp_5 = requests.head('http://httpbin.org/get')   # 发送head请求
resp_5 = requests.options('http://httpbin.org/get')    # 发送options请求
resp_6 = requests.delete('http://httpbin.org/delete')  # 发送delete请求

2.传递URL参数

# requests中使用关键字params传递URL参数
import requests

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

3.自定义header

import requests

url = 'https://www.douban.com/'
headers = {
     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6821.400 QQBrowser/10.3.3040.400'
}
resp = requests.get(url=url,headers=headers)
resp.encoding = 'utf-8'
print(resp.text)

4.自定义Cookie

import requests

cookies = {
    'cookies_are': 'working'
}
resp = requests.get('http://www.baidu.com',cookies=cookies)
for items in resp.cookies.items():
      cookies[items[0]] = items[1]
      print(cookies)

5.设置代理

proxies = {
    'http': 'http://127.0.0.10:3126',
    'https': 'http://10.10.1.10:1080'
}
requests.get('http://example.org',proxies=proxies)

6.重定向

# 在网络请求中,我们常常会遇到状态码是3开头的重定向问题,
# 在Requests中是默认开启允许重定向的,即遇到重定向时,会自动继续访问。
# 使用allow_redirects来控制是否开启重定向

resp = requests.get('http://github.com', allow_redirects=False)
print(resp.status_code)

7.禁止证书验证

"有时候我们使用了抓包工具,这个时候由于抓包工具提供的证书并不是由受信任的数字证书颁发机构颁发的,"
"所以证书的验证会失败,所以我们就需要关闭证书验证。在请求的时候把verify参数设置为False就可以关闭证书验证了。"
resp = requests.get('http://httpbin.org/post', verify=False)

8.设置超时

"设置访问超时,设置timeout参数就可"
requests.get('http://github.com', timeout=0.001)

9.接收响应

"通过Requests发起请求获取到的,是一个requests.models.Response对象。通过这个对象我们可以很方便的获取响应的内容。"
"之前通过urllib获取的响应,读取的内容都是bytes的二进制格式,需要我们自己去将结果decode()一次转换成字符串数据。"
"而Requests通过text属性,就可以获得字符串格式的响应内容。"
resp = requests.get('http://www.baidu.com')
resp.encoding = 'utf-8'   # --------------指定解码的编码格式
print(resp.text)          # --------------获取字符串格式的响应内容
print(resp.content)       # --------------获得原始的二进制数据
print(resp.json())        # --------------将json格式数据转换为字典格式的数据
print(resp.status_code)   # --------------获取响应的状态码
print(resp.headers)       # --------------获取响应的报头
print(resp.cookies)       # --------------获取服务器返回的cookies
print(resp.url)           # --------------查看访问的URL

10.案例:使用request完成登录

 

转载于:https://www.cnblogs.com/Cyzhouke/p/11458756.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值