1、get请求
# -*- coding: utf-8 -*- import requestsURL_IP = "http://b.com/index.php" pyload = {'cate':1,'id':2} headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'} def use_simple_requests():r = requests.get(URL_IP, params=pyload, headers=headers)print r.url #resuest urlprint r.headers #response headerprint r.text #response 内容(编码后) print r.content #response 内容(无编码)print r.status_code#http状态码print r.json() #输出json数据,服务器返回的不是json内容则会报错#print r.raw.read(100) #获取原始套接字相应,请求中需设置 stream=True use_simple_requests()
2、post请求
# -*- coding: utf-8 -*- import requestsURL_IP = "http://b.com/index.php" pyload = {'cate':1,'id':2} def use_simple_requests():r = requests.post('http://httpbin.org/post', data=pyload)print r.textuse_simple_requests()
3、cookie
服务器端:http://a.com/index.php
<?php$cookie_name = $_COOKIE['name']; //接受客户端发来的cookiesetcookie('name',$cookie_name.'777'); //将接受的cookie值追加'777'后发给客户端 ?>
客户端:request_demo.py
# -*- coding: utf-8 -*- import requestsURL_IP = "http://b.com/index.php" cookies = {'name':'testtest'} #设置cookie def use_simple_requests():r = requests.get(URL_IP, cookies=cookies) #request请求中带上cookieprint r.headersprint r.cookies['name'] #打印cookie use_simple_requests()
文档:http://docs.python-requests.org/en/master/user/quickstart/#make-a-request