参考
https://blog.csdn.net/pittpakk/article/details/81218566
https://blog.csdn.net/Byweiker/java/article/details/79234853
https://www.cnblogs.com/ranxf/p/7808537.html
requests库七个主要方法
requests.get() 请求指定的页面信息,并返回实体主体
requests.post() 向服务器提交post请求的方法
requests.head() 只获取html头部信息的主要方法
requests.put() 向html网页提交put请求的方法
requests.patch() 向html提交局部修改的请求
requests.delete() 向html提交删除请求
requests.request() 构造一个请求,支持以上各种方法
只说: requests.request()
源码:def request(method, url, **kwargs)
参数十几个,讲几个重点的
method: 请求方式, 'post','get'....
url: 请求地址
params: 字典或字节序列, 作为参数增加到url中,使用这个参数可以把一些键值对以?key1=value1&key2=value2的模式增加到url中
data: 字典、字节序列或 文件对象,作为Request的内容
json:JSON格式的数据,作为Request的内容
headers: 字典,放请求头的
cookies: 字典,放cookies的
files: 字典, 是用来向服务器传输文件时使用的字段
timeout: 设定超时时间,秒为单位
auth: 元组,支持HTTP认证功能
allow_redirects: True/False,默认为True,重定向开关
这俩完全是等效的
response_post = requests.post('http://httpbin.org/post', data='helloworld')
response_post1 = requests.request('post', url="http://httpbin.org/post", data='helloworld')
这俩是等效的
response_get = requests.get("http://httpbin.org/get?name=germey&age=22")
response_get1 = requests.get("http://httpbin.org/get", params={'name': 'germey', 'age': '22'})
发送文件是这样的
files = {'files':open('F:\\python\\test\\test_case\\files.txt','rb')}
r = requests.post('https://httpbin.org/post',files=files)
指定头文件和data
heard = {'Content-Type': 'application/json'}
payload = {'CountryName': '中国',
'ProvinceName': '四川省',
'L1CityName': 'chengdu',
'L2CityName': 'yibing',
'TownName': '',
'Longitude': '107.33393',
'Latitude': '33.157131',
'Language': 'CN'}
response_post = requests.post(url="http://httpbin.org/post", json=json.dumps(payload, ensure_ascii=False), headers=heard)
response_post1 = requests.post(url="http://httpbin.org/post", data=payload, headers=heard)
#ensure_ascii=True 会使用ascii 中文会乱码
Content-Type指定格式提交数据: https://blog.csdn.net/whatday/article/details/100165117
application/x-www-form-urlencoded 最常见的post提交数据的方式,以form表单形式提交数据
application/json 以json格式提交数据
multipart/form-data 一般使用来上传文件(较少用)
text/xml 它是一种使用 HTTP 作为传输协议,XML 作为编码方式的远程调用规范。
加俩headers转字典,cookies转字典的方法 以后用的时候方便
def cookie_to_dict(cookie):
itemDict = {}
items = cookie.split(';')
for item in items:
if '=' in item:
key = item.split('=')[0].replace(' ', '').replace('\n', '')
value = item.split('=')[1].replace(' ', '').replace('\n', '')
itemDict[key] = value
return itemDict
def headers_to_dict(heards):
itemDict = {}
items = heards.splitlines()
for item in items:
if ':' in item:
key = item.split(':')[0].replace(' ', '')
value = item.split(':')[1].replace(' ', '')
itemDict[key] = value
return itemDict
Response: response对象包含服务器返回的所有信息,也包含请求的Request信息
response 对象的属性:
response.status_code #HTTP请求的返回状态,200表示连接成功,其他的数值表示连接失败
response.text #HTTP相应内容的字符串形式,即,url对应的页面内容
response.encoding #从HTTP header中猜测的响应内容编码方式
response.apparent_encoding #从内容中分析出的响应内容编码方式(备选编码方式)
response.content #HTTP响应内容的二进制形式
response.headers #http响应内容的头部内容