说明:

这里主要记录一下requests模块的如下几点:

  • 1.requests模块的安装
  • 2.requests模块发送get请求
  • 3.requests模块发送post请求
  • 4.requests模块上传文件

更详细的使用参见官方文档:http://docs.python-requests.org/zh_CN/latest/

requests模块的安装

requests模块数据第三方库,这里使用pip进行安装:
pip install requests

requests模块发送get请求

requests.get(url=url, headers=headers, params=params)

  • url:请求url地址
  • headers:请求头
  • params:查询字符串
# coding:utf-8

import requests

# 请求url
url = "http://httpbin.org/get"

# 请求头
headers = {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "User-Agent": "python-requests/2.9.1",
}

# 查询字符串
params = {'name': 'Jack', 'age': '24'}

r = requests.get(url=url, headers=headers, params=params)

print r.status_code  # 获取响应状态码
print r.content  # 获取响应消息

if __name__ == "__main__":
    pass
requests模块发送post请求

requests.post(url=url, headers=headers, data=params)

  • url:请求url地址
  • headers:请求头
  • data:发送编码为表单形式的数据
# coding:utf-8

import requests

# 请求url
url = "http://httpbin.org/post"

# 请求头
headers = {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "User-Agent": "python-requests/2.9.1",
}

# 查询字符串
params = {'name': 'Jack', 'age': '24'}

r = requests.post(url=url, headers=headers, data=params)

print r.status_code  # 获取响应状态码
print r.content  # 获取响应消息

if __name__ == "__main__":
    pass
requests模块上传文件

requests.post(url=url, headers=headers, data=params, files=files)
参数说明:

  • url:请求url地址
  • headers:请求头
  • data:发送编码为表单形式的数据
  • files:上传的文件,如:
    files = {'upload_img': ('report.png', open('report.png', 'rb'), 'image/png')}
    参数说明:
    • 1.report.png:文件名
    • 2.open('report.png', 'rb'):文件内容
    • 3.image/png:文件类型
# coding:utf-8

import requests

# 请求url
url = "http://httpbin.org/post"

# 请求头
headers = {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "User-Agent": "python/2.9.1",
}

# 查询字符串
params = {'name': 'Jack', 'age': '24'}

# 文件
files = {'upload_img': ('report.xlsx', open('report.xlsx', 'rb'), 'image/png')}
r = requests.post(url=url, data=params, headers=headers, files=files)

print r.status_code  # 获取响应状态码
print r.content  # 获取响应消息

if __name__ == "__main__":
    pass