1. 程式人生 > >[python 學習] requests 庫的使用

[python 學習] requests 庫的使用

python 客戶 use chrome 接受 tex () requests http

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 庫的使用