码迷,mamicode.com
首页 > 编程语言 > 详细

[python 学习] requests 库的使用

时间:2017-08-27 22:27:21      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:like   setcookie   打印   quick   class   编码   response   学习   url   

1、get请求

# -*- coding: utf-8 -*-
import requests

URL_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 url
    print r.headers    #response header
    print 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 requests

URL_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.text

use_simple_requests()

3、cookie

  服务器端:http://a.com/index.php

<?php
    $cookie_name = $_COOKIE[‘name‘];       //接受客户端发来的cookie
    setcookie(‘name‘,$cookie_name.‘777‘);  //将接受的cookie值追加‘777‘后发给客户端
?>

  客户端:request_demo.py

# -*- coding: utf-8 -*-
import requests

URL_IP = "http://b.com/index.php"
cookies = {name:testtest} #设置cookie
def use_simple_requests():
    r = requests.get(URL_IP, cookies=cookies) #request请求中带上cookie
    print r.headers
    print r.cookies[name] #打印cookie

use_simple_requests()

技术分享

文档:http://docs.python-requests.org/en/master/user/quickstart/#make-a-request

[python 学习] requests 库的使用

标签:like   setcookie   打印   quick   class   编码   response   学习   url   

原文地址:http://www.cnblogs.com/natian-ws/p/7440859.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!