码迷,mamicode.com
首页 > 其他好文 > 详细

~request库的使用

时间:2019-09-10 18:14:54      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:读取   code   遇到   安装   encoding   字典   red   字符串   需要   

官方文档:

安装:pip install request

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

1.请求方法

import requests        # 导入requests

resp_1 = requests.get(http://httpbin.org/post)    # 发送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)       # --------------获得原始的二进制数据
resp.json()               # --------------将json格式数据转换为字典格式的数据
print(resp.status_code)   # --------------获取响应的状态码
print(resp.headers)       # --------------获取响应的报头
print(resp.cookies)       # --------------获取服务器返回的cookies
print(resp.url)           # --------------查看访问的URL

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

技术图片

 

~request库的使用

标签:读取   code   遇到   安装   encoding   字典   red   字符串   需要   

原文地址:https://www.cnblogs.com/Cyzhouke/p/11458756.html

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