python request 模塊詳細介紹
request
Requests 是使用 Apache2 Licensed 許可證的 基于Python開發(fā)的HTTP 庫,其在Python內(nèi)置模塊的基礎(chǔ)上進行了高度的封裝,從而使得Pythoner進行網(wǎng)絡(luò)請求時,變得美好了許多,使用Requests可以輕而易舉的完成瀏覽器可有的任何操作。
GET 請求
# 1、無參數(shù)實例
import requests
ret = requests.get('https://github.com/timeline.json')
print ret.url
print ret.text
# 2、有參數(shù)實例
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
ret = requests.get("http://httpbin.org/get", params=payload)
print ret.url
print ret.text
POST 請求
# 1、基本POST實例
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
ret = requests.post("http://httpbin.org/post", data=payload)
print ret.text
# 2、發(fā)送請求頭和數(shù)據(jù)實例
import requests
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
ret = requests.post(url, data=json.dumps(payload), headers=headers)
print ret.text
print ret.cookies
其他請求
requests.get(url, params=None, **kwargs) requests.post(url, data=None, json=None, **kwargs) requests.put(url, data=None, **kwargs) requests.head(url, **kwargs) requests.delete(url, **kwargs) requests.patch(url, data=None, **kwargs) requests.options(url, **kwargs) # 以上方法均是在此方法的基礎(chǔ)上構(gòu)建 requests.request(method, url, **kwargs)
requests.request() 參數(shù)
method:提交方式 get/post 。
url:提交地址。
params:在URL上傳遞的參數(shù),GET形式傳遞到后臺,例如向http://www.oldboyyede.com上傳數(shù)據(jù)。
requests.request(
method = 'GET',
url = 'http://www.oldboyyede.com',
params = { 'k1' : 'v1' , 'k2' : 'v2' }
)
# http://www.oldboyyede.com?k1=v1&k2=v2
data:在請求體里面?zhèn)鬟f的數(shù)據(jù),后面可以是字典,字節(jié)等數(shù)據(jù)類型。
requests.request(
method = 'POST',
url = 'http://www.oldboyyede.com',
# data= { 'k1' : 'v1' , 'k2' : 'v2' , 'x':[1,2,3]}
data=" user=wjw&pwd=123123 "
)
json:在請求體里面?zhèn)鬟f數(shù)據(jù),把整體序列化成一個大字符串,字典中嵌套字典的話用JSON 。
requests.request(
method = 'POST',
url = 'http://www.oldboyyede.com',
json= { 'k1' : 'v1' , 'k2' : 'v2' }
)
# "{ 'k1' : 'v1' , 'k2' : 'v2' }"
headers:請求頭。
一定要添加瀏覽器,不然可能會遇到網(wǎng)絡(luò)防火墻

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:58.0) Gecko/20100101 Firefox/58.0'}
# 一定要添加瀏覽器,不然可能會遇到網(wǎng)絡(luò)防火墻攔截你的請求
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:58.0) Gecko/20100101 Firefox/58.0'}
r1 = requests.get(
url='http://dig.chouti.com/',
headers=headers
)
files:上傳文件對象。
# 模塊的詳細使用
import requests
requests.post(
url='xxxxxx',
files={
# 'f1':open('s1.py','rb')
# 可以上傳元祖的形式上傳,sssss1.py為后臺獲取的名稱
'f1': open('sssss1.py',('s1.py', 'rb'))
}
)
參數(shù)實例
def param_method_url():
# requests.request(method='get', url='http://127.0.0.1:8000/test/')
# requests.request(method='post', url='http://127.0.0.1:8000/test/')
pass
def param_param():
# - 可以是字典
# - 可以是字符串
# - 可以是字節(jié)(ascii編碼以內(nèi))
# requests.request(method='get',
# url='http://127.0.0.1:8000/test/',
# params={'k1': 'v1', 'k2': '水電費'})
# requests.request(method='get',
# url='http://127.0.0.1:8000/test/',
# params="k1=v1&k2=水電費&k3=v3&k3=vv3")
# requests.request(method='get',
# url='http://127.0.0.1:8000/test/',
# params=bytes("k1=v1&k2=k2&k3=v3&k3=vv3", encoding='utf8'))
# 錯誤
# requests.request(method='get',
# url='http://127.0.0.1:8000/test/',
# params=bytes("k1=v1&k2=水電費&k3=v3&k3=vv3", encoding='utf8'))
pass
def param_data():
# 可以是字典
# 可以是字符串
# 可以是字節(jié)
# 可以是文件對象
# requests.request(method='POST',
# url='http://127.0.0.1:8000/test/',
# data={'k1': 'v1', 'k2': '水電費'})
# requests.request(method='POST',
# url='http://127.0.0.1:8000/test/',
# data="k1=v1; k2=v2; k3=v3; k3=v4"
# )
# requests.request(method='POST',
# url='http://127.0.0.1:8000/test/',
# data="k1=v1;k2=v2;k3=v3;k3=v4",
# headers={'Content-Type': 'application/x-www-form-urlencoded'}
# )
# requests.request(method='POST',
# url='http://127.0.0.1:8000/test/',
# data=open('data_file.py', mode='r', encoding='utf-8'), # 文件內(nèi)容是:k1=v1;k2=v2;k3=v3;k3=v4
# headers={'Content-Type': 'application/x-www-form-urlencoded'}
# )
pass
def param_json():
# 將json中對應(yīng)的數(shù)據(jù)進行序列化成一個字符串,json.dumps(...)
# 然后發(fā)送到服務(wù)器端的body中,并且Content-Type是 {'Content-Type': 'application/json'}
requests.request(method='POST',
url='http://127.0.0.1:8000/test/',
json={'k1': 'v1', 'k2': '水電費'})
def param_headers():
# 發(fā)送請求頭到服務(wù)器端
requests.request(method='POST',
url='http://127.0.0.1:8000/test/',
json={'k1': 'v1', 'k2': '水電費'},
headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
def param_cookies():
# 發(fā)送Cookie到服務(wù)器端
requests.request(method='POST',
url='http://127.0.0.1:8000/test/',
data={'k1': 'v1', 'k2': 'v2'},
cookies={'cook1': 'value1'},
)
# 也可以使用CookieJar(字典形式就是在此基礎(chǔ)上封裝)
from http.cookiejar import CookieJar
from http.cookiejar import Cookie
obj = CookieJar()
obj.set_cookie(Cookie(version=0, name='c1', value='v1', port=None, domain='', path='/', secure=False, expires=None,
discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False,
port_specified=False, domain_specified=False, domain_initial_dot=False, path_specified=False)
)
requests.request(method='POST',
url='http://127.0.0.1:8000/test/',
data={'k1': 'v1', 'k2': 'v2'},
cookies=obj)
def param_files():
# 發(fā)送文件
# file_dict = {
# 'f1': open('readme', 'rb')
# }
# requests.request(method='POST',
# url='http://127.0.0.1:8000/test/',
# files=file_dict)
# 發(fā)送文件,定制文件名
# file_dict = {
# 'f1': ('test.txt', open('readme', 'rb'))
# }
# requests.request(method='POST',
# url='http://127.0.0.1:8000/test/',
# files=file_dict)
# 發(fā)送文件,定制文件名
# file_dict = {
# 'f1': ('test.txt', "hahsfaksfa9kasdjflaksdjf")
# }
# requests.request(method='POST',
# url='http://127.0.0.1:8000/test/',
# files=file_dict)
# 發(fā)送文件,定制文件名
# file_dict = {
# 'f1': ('test.txt', "hahsfaksfa9kasdjflaksdjf", 'application/text', {'k1': '0'})
# }
# requests.request(method='POST',
# url='http://127.0.0.1:8000/test/',
# files=file_dict)
pass
<br>
# 做基本認(rèn)證 header中加密的用戶名和密碼
def param_auth():
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
ret = requests.get('https://api.github.com/user', auth=HTTPBasicAuth('wangjiawei', 'sdfasdfasdf'))
print(ret.text)
# ret = requests.get('http://192.168.1.1',
# auth=HTTPBasicAuth('admin', 'admin'))
# ret.encoding = 'gbk'
# print(ret.text)
# ret = requests.get('http://httpbin.org/digest-auth/auth/user/pass', auth=HTTPDigestAuth('user', 'pass'))
# print(ret)
#
# 請求和響應(yīng)的超時時間
def param_timeout():
# ret = requests.get('http://google.com/', timeout=1)
# print(ret)
# ret = requests.get('http://google.com/', timeout=(5, 1))
# print(ret)
pass
<br>
# 是允許否重定向
def param_allow_redirects():
ret = requests.get('http://127.0.0.1:8000/test/', allow_redirects=False)
print(ret.text)
<br>
# 代理 出口IP 不是本機IP。 流程是:先給代理發(fā),代理幫助我們向目的地址發(fā)。
def param_proxies():
# proxies = {
# "http": "61.172.249.96:80",
# "https": "http://61.185.219.126:3128",
# }
# proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}
# ret = requests.get("http://www.proxy#/123456", proxies=proxies)
# print(ret.headers)
# from requests.auth import HTTPProxyAuth
#
# proxyDict = {
# 'http': '77.75.105.165',
# 'https': '77.75.105.165'
# }
# auth = HTTPProxyAuth('username', 'mypassword')
#
# r = requests.get("http://www.google.com", proxies=proxyDict, auth=auth)
# print(r.text)
pass
<br>
# 流形式 比如下片
def param_stream():
ret = requests.get('http://127.0.0.1:8000/test/', stream=True)
print(ret.content)
ret.close()
# from contextlib import closing
# with closing(requests.get('http://httpbin.org/get', stream=True)) as r:
# # 在此處理響應(yīng)。迭代處理
# for i in r.iter_content():
# print(i)
def requests_session():
import requests
session = requests.Session()
### 1、首先登陸任何頁面,獲取cookie
i1 = session.get(url="http://dig.chouti.com/help/service")
### 2、用戶登陸,攜帶上一次的cookie,后臺對cookie中的 gpsd 進行授權(quán)
i2 = session.post(
url="http://dig.chouti.com/login",
data={
'phone': "8612345678977",
'password': "xxxxxx",
'oneMonth': ""
}
)
i3 = session.post(
url="http://dig.chouti.com/link/vote?linksId=8589623",
)
print(i3.text)
http 與 https 區(qū)別
- http
本質(zhì)上就是 socket,http 請求不安全,因為沒有任何的加密措施。
- https
擁有加密措施,ssh 加密,有證書一說,服務(wù)器給請求的客戶端頒發(fā)證書,客戶端使用證書對客戶端發(fā)送的數(shù)據(jù)加密成密文,然后發(fā)送給服務(wù)器,服務(wù)器通過證書進行解密,檢測是否是匹配的,進行傳輸信息。通信間必須使用證書。cert參數(shù)是證書,主動提供證書,可以自己制作(缺錢的話),比如證書是“fuck.pem”,cert=('fuck.pem'),必須使用證書,如果沒有證書則不能進行通信。還有一類證書需要自己買的第三方可信賴的證書,系統(tǒng)在創(chuàng)建(一裝機)的時候直接植入證書,廠商幫忙做驗證,這就是有錢和沒錢的區(qū)別,用戶不需要自己在瀏覽器上安裝證書了,pem是證書的格式,cert=('fuck.crt','xxx.key'),和自己辦法的沒區(qū)別,需要啥樣給啥樣,完成的事都是做加密使用。還有一個參數(shù)叫 verify,如果 verify=False,則表示忽略證書,直接發(fā)請求直接拿結(jié)果,一般網(wǎng)站是允許用的,但是服務(wù)器必須要證書也白搭。
以上就是python request 模塊詳細介紹的詳細內(nèi)容,更多關(guān)于python request 模塊的資料請關(guān)注腳本之家其它相關(guān)文章!
- 淺析Python requests 模塊
- Python使用requests模塊爬取百度翻譯
- Python grequests模塊使用場景及代碼實例
- Python requests模塊安裝及使用教程圖解
- Python requests模塊cookie實例解析
- python爬蟲開發(fā)之Request模塊從安裝到詳細使用方法與實例全解
- Python3離線安裝Requests模塊問題
- python爬蟲 基于requests模塊的get請求實現(xiàn)詳解
- python爬蟲 基于requests模塊發(fā)起ajax的get請求實現(xiàn)解析
- python利用re,bs4,requests模塊獲取股票數(shù)據(jù)
- Python實現(xiàn)使用request模塊下載圖片demo示例
- Python3使用requests模塊實現(xiàn)顯示下載進度的方法詳解
相關(guān)文章
Python實現(xiàn)中文數(shù)字轉(zhuǎn)換為阿拉伯?dāng)?shù)字的方法示例
這篇文章主要介紹了Python實現(xiàn)中文數(shù)字轉(zhuǎn)換為阿拉伯?dāng)?shù)字的方法,涉及Python字符串遍歷、轉(zhuǎn)換相關(guān)操作技巧,需要的朋友可以參考下2017-05-05
在Lighttpd服務(wù)器中運行Django應(yīng)用的方法
這篇文章主要介紹了在Lighttpd服務(wù)器中運行Django應(yīng)用的方法,本文所采用的是最流行的FastCGI模塊,包括同時運行多個Django應(yīng)用的方法,需要的朋友可以參考下2015-07-07
python BitMap算法處理20億隨機整數(shù)去重
這篇文章主要為大家介紹了python BitMap算法處理20億隨機整數(shù)去重,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01

