python request请求代码快速复制使用指南

普通请求get

import requests
response = requests.get('www.baidu.com')  不带参数

带参数
urlpara = {
    'wd':'iphone&ipad',
    'rsv_spt':'1'
}

response = requests.get('https://www.baidu.com/s',params=urlpara)
response.text #请求结果

普通请求post

基本post请求

headers = {
    'user-agent': 'my-app/0.0.1', 
    'auth-type': 'jwt-token'
}

r = requests.post("http://httpbin.org/post", headers=headers)带请求头

payload = {'key1': 'value1', 'key2': 'value2'}

r = requests.post("http://httpbin.org/post", data=payload) 带数据包

注意,很多人请求头嫌难打的去https://curlconverter.com/这个网站可以快速构建本机的请求头,按照情况使用

json数据请求

import requests,json

payload = {
    "Overall":"良好",
    "Progress":"30%",
    "Problems":[
        {
            "No" : 1,
            "desc": "问题1...."
        },
        {
            "No" : 2,
            "desc": "问题2...."
        },
    ]
}

r = requests.post("http://httpbin.org/post", data=json.dumps(payload))

或者

r = requests.post("http://httpbin.org/post", json=payload)
content = r.json()

文件请求

files = {'file': open('report.xls', 'rb')}
response = requests.post('https://api.example.com/upload', files=files)

代理请求

import requests

proxies = {
  'http': 'http://127.0.0.1:8888',
  'https': 'http://127.0.0.1:8888',
}

response = requests.get('www.baidu.com', proxies=proxies)
print(response.text)

下载图片

import requests
file_path = os.path.join(file_dir, image_name) 
#路径拼接 file_dir是你默认的存储路径自定义 image_name为保存的照片名字
img_request = requests.get(url)
with open(file_path, 'wb') as f:
	f.write(img_request.content)

请求特殊情况

超时

response = requests.get('www.baidu.com', timeout=0.01)

获取请求状态响应码

response = requests.get('www.baidu.com')
response.status_code 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值