一. Requests: 讓 HTTP 服務(wù)人類
雖然Python的標(biāo)準(zhǔn)庫中 urllib2 模塊已經(jīng)包含了平常我們使用的大多數(shù)功能,但是它的 API 使用起來讓人感覺不太好,而 Requests 自稱 “HTTP for Humans”,說明使用更簡潔方便。
requests 唯一的一個(gè)非轉(zhuǎn)基因的 Python HTTP 庫,人類可以安全享用:
requests 繼承了urllib2的所有特性。Requests支持HTTP連接保持和連接池,支持使用cookie保持會話,支持文件上傳,支持自動確定響應(yīng)內(nèi)容的編碼,支持國際化的 URL 和 POST 數(shù)據(jù)自動編碼。
requests 的底層實(shí)現(xiàn)其實(shí)就是 urllib3
requests 的文檔非常完備,中文文檔也相當(dāng)不錯(cuò)
Requests 能完全滿足當(dāng)前網(wǎng)絡(luò)的需求,支持Python 2.6以上。
開源地址:https://github.com/kennethreitz/requests
中文文檔 API:http://docs.python-requests.org/zh_CN/latest/index.html
安裝方式
利用 pip 安裝 或者利用 easy_install 都可以完成安裝:
pip install requests
或 easy_install requests
二. Requests使用
GET請求和POST請求
- 最基本的GET請求
最基本的GET請求可以直接用get方法
response = requests.get("http://www.baidu.com/")
也可以這么寫
# response = requests.request("get", "http://www.baidu.com/")
添加 headers 和 查詢參數(shù):
如果想添加 headers,可以傳入headers參數(shù)來增加請求頭中的headers信息。如果要將參數(shù)放在url中傳遞,可以利用params參數(shù)。
示例:百度搜索
import requests
kw = {'wd':'長城'}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
}
# params 接收一個(gè)字典或者字符串的查詢參數(shù),字典類型自動轉(zhuǎn)換為url編碼,不需要urlencode()
response = requests.get("http://www.baidu.com/s?", params = kw, headers = headers)
# 查看響應(yīng)內(nèi)容,response.text 返回的是Unicode格式的數(shù)據(jù)
print(response.text)
# 查看響應(yīng)內(nèi)容,response.content返回的字節(jié)流數(shù)據(jù)
print(respones.content)
# 查看完整url地址
print(response.url)
# 查看響應(yīng)頭部字符編碼
print(response.encoding)
# 查看響應(yīng)碼
print(response.status_code)
使用response.text 時(shí),Requests 會基于 HTTP 響應(yīng)的文本編碼自動解碼響應(yīng)內(nèi)容,大多數(shù) Unicode 字符集都能被無縫地解碼。
使用response.content 時(shí),返回的是服務(wù)器響應(yīng)數(shù)據(jù)的原始二進(jìn)制字節(jié)流,可以用來保存圖片等二進(jìn)制文件。
- 基本POST請求(data參數(shù))
1. 最基本的GET請求可以直接用post方法
response = requests.post("http://www.baidu.com/", data = data)
2. 傳入data數(shù)據(jù)
對于 POST 請求來說,我們一般需要為它增加一些參數(shù)。那么最基本的傳參方法可以利用data這個(gè)參數(shù)。
示例:有道翻譯
import requests
import json
def youdaoAPI(kw):
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
response = requests.post(url, data=kw, headers=header)
res = response.content
# tgt = json.loads(res) # json解析
tgt = res.json() # 自帶json解析
print(tgt["translateResult"])
if __name__ == '__main__':
kw = input("請輸入你想翻譯的內(nèi)容:")
timet = int(time.time() * 1000)
data = {
"i": kw,
"from": "AUTO",
"to": "AUTO",
"smartresult": "dict",
"client": "fanyideskweb",
"salt": timet,
"sign": "f66461b42fe9edb6d88230788fb33cfb",
"doctype": "json",
"version": "2.1",
"keyfrom": "fanyi.web",
"action ": "FY_BY_REALTIME",
"typoResult ": "false",
}
youdaoAPI(data)
- 代理(proxies參數(shù))
如果需要使用代理,你可以通過為任意請求方法提供proxies參數(shù)來配置單個(gè)請求:
import requests
# 根據(jù)協(xié)議類型,選擇不同的代理
proxies = {
"http": "http://12.34.56.79:9527",
"https": "http://12.34.56.79:9527",
}
# 帶密碼代理
# proxies = {"https": "http://User1:123456@10.3.132.6:808"}
response = requests.get("http://www.baidu.com", proxies = proxies)
print(response.text)
- web客戶端驗(yàn)證
如果是Web客戶端驗(yàn)證,需要添加 auth = (賬戶名, 密碼)
import requests
auth=('test', '123456')
response = requests.get('https://api.github.com/user', auth = auth)
print(response.text)
三. Cookies 和 Session
- Cookies
如果一個(gè)響應(yīng)中包含了cookie,那么我們可以利用 cookies參數(shù)拿到:
import requests
response = requests.get("http://www.baidu.com/")
# 返回CookieJar對象:
cookiejar = response.cookies
# 將CookieJar轉(zhuǎn)為字典:
cookiedict = requests.utils.dict_from_cookiejar(cookiejar)
print(cookiejar) # <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
print(cookiedict) # {'BDORZ': '27315'}
- Session
在 requests 里,session對象是一個(gè)非常常用的對象,這個(gè)對象代表一次用戶會話:從客戶端瀏覽器連接服務(wù)器開始,到客戶端瀏覽器與服務(wù)器斷開。
會話能讓我們在跨請求時(shí)候保持某些參數(shù),比如在同一個(gè) Session 實(shí)例發(fā)出的所有請求之間保持 cookie 。
示例:實(shí)現(xiàn)筆趣閣登錄
import requests
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"
}
session = requests.session() # 保存cookie
# 筆趣閣登錄
url = "https://www.biquge5200.cc/u/login.htm"
data = {
# 用戶名: niejeff, 密碼: 123456
"name": "niejeff",
"password": "E10ADC3949BA59ABBE56E057F20F883E",
"autoLogin": "1",
"autologin": "1"
}
# 登錄
response = session.post(url, data=data, headers=headers)
print(response.text)
- 處理HTTPS請求 SSL證書驗(yàn)證
Requests也可以為HTTPS請求驗(yàn)證SSL證書:
import requests
# 要想檢查某個(gè)主機(jī)的SSL證書,你可以使用 verify 參數(shù)(也可以不寫)
response = requests.get("https://www.baidu.com/", verify=True)
# 忽略驗(yàn)證, 可以省略不寫或設(shè)置為verify=false
response = requests.get("https://www.baidu.com/")
print(response.text)
如果SSL證書驗(yàn)證不通過,或者不信任服務(wù)器的安全證書,則會報(bào)出SSLError,據(jù)說 12306 證書是自己做的:
來測試一下:
import requests
response = requests.get("https://www.12306.cn/mormhweb/")
print(response.text)
果然:
SSLError: ("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')],)",)
如果我們想跳過 12306 的證書驗(yàn)證,把 verify 設(shè)置為 False 就可以正常請求了。
import requests
response = requests.get("https://www.12306.cn/mormhweb/",verify=False)
print response.text