Fork me on GitHub

python接口自动化系列 - requests库的基础使用01

一、安装

利用 pip 安装:$ pip install requests 

requests 方法

描述
delete(urlargs) 发送 DELETE 请求到指定 url
get(urlparams, args) 发送 GET 请求到指定 url
head(urlargs) 发送 HEAD 请求到指定 url
patch(urldata, args) 发送 PATCH 请求到指定 url
post(urldata, json, args) 发送 POST 请求到指定 url
put(urldata, args) 发送 PUT 请求到指定 url
request(methodurlargs) 向指定的 url 发送指定的请求方法

二、GET请求

使用 requests.request() 发送 get 请求:

# 导入 requests 包
import requests

 
kw = {'s':'python 教程'}

# 设置请求头
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
 
# params 接收一个字典或者字符串的查询参数,字典类型自动转换为url编码,不需要urlencode()
response = requests.get("https://www.runoob.com/", params = kw, headers = headers)

# 查看响应状态码
print (response.status_code)

# 查看响应头部字符编码
print (response.encoding)

# 查看完整url地址
print (response.url)

# 查看响应内容,response.text 返回的是Unicode格式的数据
print(response.text)

返回结果:

200
UTF-8
https://www.runoob.com/?s=python+%E6%95%99%E7%A8%8B

... 其他内容...

三、POST请求

post() 方法可以发送 POST 请求到指定 url,一般格式如下:

requests.post(url, data={key: value}, json={key: value}, args)
  • url 请求 url。

  • data 参数为要发送到指定 url 的字典、元组列表、字节或文件对象。

  • json 参数为要发送到指定 url 的 JSON 对象。

  • args 为其他参数,比如 cookies、headers、verify等。

示例:

import json
import requests

url = 'http://httpbin.org/post'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))
print(r.json())

返回结果:

{'args': {}, 'data': '{"some": "data"}', 'files': {}, 'form': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Content-Length': '16', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.24.0', 'X-Amzn-Trace-Id': 'Root=1-63b3d897-1820a44923eb0e5753e03dae'}, 'json': {'some': 'data'}, 'origin': '202.60.224.33', 'url': 'http://httpbin.org/post'}

四、自定义headers和cookies

"""自定义headers"""
import requests
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}

r = requests.get(url, headers=headers)
print(r.json())

"""自定义cookies"""
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
cookies2 = {'cookies_are': 'working'}

r = requests.get(url, cookies=cookies)
print(r.json())

返回结果:

{'message': 'Not Found', 'documentation_url': 'https://docs.github.com/rest'}
{'cookies': {'cookies_are': 'working'}}

五、SSL证书验证

 当发送请求如果报以上错误时,可以在请求方法里加多一个字段 verify=False ,就可以解决此问题;此操作是为了免去验证步骤

import requests
requests.packages.urllib3.disable_warnings()
url = 'https://www.imooc.com'
res = requests.get(url, verify=False)
print(res.text)

返回结果:

 

 

 

  

  

 

posted @ 2023-01-04 21:16  橘子偏爱橙子  阅读(49)  评论(0编辑  收藏  举报