安装
pip install requests
请求
发起get请求
# 利用Python发起HTTP请求
import requests
# 使用get方式请求百度首页
response = requests.get("https://www.baidu.com/")
get请求参数传递
param = {"wd": "Python"}
get_url = 'https://www.baidu.com'
response = requests.get(get_url, params=param)
'''
最终拼接效果为:
https://www.baidu.com/s?wd=Python
'''
print(response.url)
输出:
https://www.baidu.com/?wd=Python
发起POST请求
提交的数据必须放在消息主体中
语法如下:
requests.post(url, data)
注:data需为字典类型的提交数据
示例1:(常规用法)
import requests
url = 'http://httpbin.org/post'
data = {'key1': 'value1', 'key2': 'value2'}
r = requests.post(url, data)
示例2:(json形式)
import requests, json
url_json = 'http://httpbin.org/post'
data_json = json.dumps({'stock_no': '600585', 'price': '52.12'}) # dumps:可以将python对象解码为json数据
res = requests.post(url_json, data_json)
示例3:(文件流形式)
import requests
url_mul = 'http://httpbin.org/post'
files = {'file': open('./report.txt', 'rb')} # 设置要被打开的文件
res = requests.post(url_mul, files=files)
其他参数传递
seesion请求传递
import requests
s = requests.Session()
r = s.get('http://httpbin.org/cookies', cookies={'from-my': 'browser'})
print(r.text)
r = s.get('http://httpbin.org/cookies')
print(r.text)
输出:
{
"cookies": {
"from-my": "browser"
}
}
{
"cookies": {}
}
手动添加cookie信息操作
# 手动添加cookie信息操作
r = s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
print(r.text)
输出:
{
"cookies": {
"sessioncookie": "123456789"
}
}
header参数传递
from requests import Request, Session
s = Session()
url = 'http://httpbin.org/'
data = {"s": "Golang"}
header = {'Accept-Encoding': 'identity, deflate, compress, gzip',
'Accept': '*/*', 'User-Agent': 'python-requests/0.13.1'}
req = Request('GET', url, data=data, headers=header)
print(req.prepare())
prepare_obj = req.prepare()
resp = s.send(prepare_obj)
print(resp)
输出:
<PreparedRequest [GET]>
<Response [200]>
或是选择仍使用参数传递方式
response = requests.get(url, params=data, headers=header)
print(response.status_code)
响应
requests请求后响应结果有多个属性
以下针对比较常用的做相关说明:
# 查看响应内容
print(response.text.encode())
# 查看完整的url地址
print(response.url)
# 查看响应头部的字符编码
print(response.encoding)
# 查看响应码
print(response.status_code)
输出:
b'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>\xc3\xa7\xc2\x99\xc2\xbe\xc3\xa5\xc2\xba\xc2\xa6\xc3\xa4\xc2\xb8\xc2\x80\xc3\xa4\xc2\xb8\xc2\x8b\xc3\xaf\xc2\xbc\xc2\x8c\xc3\xa4\xc2\xbd\xc2\xa0\xc3\xa5\xc2\xb0\xc2\xb1\xc3\xa7\xc2\x9f\xc2\xa5\xc3\xa9\xc2\x81\xc2\x93</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=\xc3\xa7\xc2\x99\xc2\xbe\xc3\xa5\xc2\xba\xc2\xa6\xc3\xa4\xc2\xb8\xc2\x80\xc3\xa4\xc2\xb8\xc2\x8b class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>\xc3\xa6\xc2\x96\xc2\xb0\xc3\xa9\xc2\x97\xc2\xbb</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>\xc3\xa5\xc2\x9c\xc2\xb0\xc3\xa5\xc2\x9b\xc2\xbe</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>\xc3\xa8\xc2\xa7\xc2\x86\xc3\xa9\xc2\xa2\xc2\x91</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>\xc3\xa8\xc2\xb4\xc2\xb4\xc3\xa5\xc2\x90\xc2\xa7</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>\xc3\xa7\xc2\x99\xc2\xbb\xc3\xa5\xc2\xbd\xc2\x95</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">\xc3\xa7\xc2\x99\xc2\xbb\xc3\xa5\xc2\xbd\xc2\x95</a>');\r\n </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">\xc3\xa6\xc2\x9b\xc2\xb4\xc3\xa5\xc2\xa4\xc2\x9a\xc3\xa4\xc2\xba\xc2\xa7\xc3\xa5\xc2\x93\xc2\x81</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>\xc3\xa5\xc2\x85\xc2\xb3\xc3\xa4\xc2\xba\xc2\x8e\xc3\xa7\xc2\x99\xc2\xbe\xc3\xa5\xc2\xba\xc2\xa6</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>\xc3\xa4\xc2\xbd\xc2\xbf\xc3\xa7\xc2\x94\xc2\xa8\xc3\xa7\xc2\x99\xc2\xbe\xc3\xa5\xc2\xba\xc2\xa6\xc3\xa5\xc2\x89\xc2\x8d\xc3\xa5\xc2\xbf\xc2\x85\xc3\xa8\xc2\xaf\xc2\xbb</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>\xc3\xa6\xc2\x84\xc2\x8f\xc3\xa8\xc2\xa7\xc2\x81\xc3\xa5\xc2\x8f\xc2\x8d\xc3\xa9\xc2\xa6\xc2\x88</a> \xc3\xa4\xc2\xba\xc2\xacICP\xc3\xa8\xc2\xaf\xc2\x81030173\xc3\xa5\xc2\x8f\xc2\xb7 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'
https://www.baidu.com/
ISO-8859-1
200
响应处理
此处以响应码为例做示例后续处理操作
先判断响应码,然后对text属性设置编码,最后获取所需的文本
若失败则做其他处理
if response.status_code == 200:
print("ok")
print(response.text.encode())
else:
print('fail')
业务代码响应code的处理方式
仿照switch/case用法
switcher集合中存放业务错误响应代码
import time
import requests
import json
def deal(code):
switcher = {
'40001': 'page error1',
'40002': 'page error2',
'40003': 'page error3',
}
msg = switcher.get(code, 'ok')
# 没找到对应的code 则测试成功
if msg != 'ok':
with open('error.txt', 'w') as f:
data_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
f.write(data_str + '\n' + msg)
else:
print("ok!")
response = requests.post("https://www.hzcourse.com/web/refbook/queryResourcesCount")
json_data = response.text
cc = json.loads(json_data)['code']
deal('cc')