Requests:
雖然Python的標準庫中 urllib 模塊已經包含了平常我們使用的大多數功能,但是它的 API 使用起來讓人感覺不太好,而 Requests 自稱 "HTTP for Humans",說明使用更簡潔方便。
Requests 唯一的一個非轉基因的 Python HTTP 庫,人類可以安全享用:)
Requests 繼承了urllib的所有特性。Requests支持HTTP連接保持和連接池,支持使用cookie保持會話,支持文件上傳,支持自動確定響應內容的編碼,支持國際化的 URL 和 POST 數據自動編碼。
requests 的底層實現其實就是 urllib
Requests的文檔非常完備,中文文檔也相當不錯。Requests能完全滿足當前網絡的需求,支持Python 2.6--3.5,而且能在PyPy下完美運行。
開源地址: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
基本GET請求(headers參數 和 parmas參數)
1. 最基本的GET請求可以直接用get方法
response = requests.get("http://www.baidu.com/")
# 也可以這麼寫
# response = requests.request("get", "http://www.baidu.com/")
2. 添加 headers 和 查詢參數
如果想添加 headers,可以傳入headers
參數來增加請求頭中的headers信息。如果要將參數放在url中傳遞,可以利用 params
參數。
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 接收一個字典或者字符串的查詢參數,字典類型自動轉換爲url編碼,不需要urlencode()
response = requests.get("http://www.baidu.com/s?", params = kw, headers = headers)
# 查看響應內容,response.text 返回的是Unicode格式的數據
print (response.text)
# 查看響應內容,response.content返回的字節流數據
print (respones.content)
# 查看完整url地址
print (response.url)
# 查看響應頭部字符編碼
print (response.encoding)
# 查看響應碼
print (response.status_code)
運行結果
......
......
'http://www.baidu.com/s?wd=%E9%95%BF%E5%9F%8E'
'utf-8'
200
使用response.text 時,Requests 會基於 HTTP 響應的文本編碼自動解碼響應內容,大多數 Unicode 字符集都能被無縫地解碼。
使用response.content 時,返回的是服務器響應數據的原始二進制字節流,可以用來保存圖片等二進制文件。
小栗子
通過requests獲取新浪首頁
#coding=utf-8
import requests
response = requests.get("http://www.sina.com")
print(response.request.headers)
print(response.content.decode())
結果
{'User-Agent': 'python-requests/2.12.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
<!DOCTYPE html>
<!-- [ published at 2017-06-09 15:15:23 ] -->
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>新浪首頁</title>
<meta name="keywords" content="新浪,新浪網,SINA,sina,sina.com.cn,新浪首頁,門戶,資訊" />
...
#coding=utf-8
import requests
response = requests.get("http://www.sina.com")
print(response.request.headers)
print(response.text)
結果
{'User-Agent': 'python-requests/2.12.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
<!DOCTYPE html>
<!-- [ published at 2017-06-09 15:18:10 ] -->
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>新浪首页</title>
<meta name="keywords" content="新浪,新浪网,SINA,sina,sina.com.cn,新浪首页,门户,资讯" />
<meta name="description" content="新浪网为全çƒç”¨æˆ·24å°æ—¶æ供全é¢åŠæ—¶çš„ä¸æ–‡èµ„讯,内容覆盖国内外çªå‘新闻事件ã€ä½“å›èµ›äº‹ã€å¨±ä¹æ—¶å°šã€äº§ä¸šèµ„讯ã€å®žç”¨ä¿¡æ¯ç‰ï¼Œè®¾æœ‰æ–°é—»ã€ä½“育ã€å¨±ä¹ã€è´¢ç»ã€ç§‘技ã€æˆ¿äº§ã€æ±½è½¦ç‰30多个内容频é“,åŒæ—¶å¼€è®¾åšå®¢ã€è§†é¢‘ã€è®ºå›ç‰è‡ªç”±äº’动交æµç©ºé—´ã€‚" />
<link rel="mask-icon" sizes="any" href="//www.sina.com.cn/favicon.svg" color="red">
`
產生問題的原因分析
- requests默認自帶的Accept-Encoding導致或者新浪默認發送的就是壓縮之後的網頁
- 但是爲什麼content.read()沒有問題,因爲requests,自帶解壓壓縮網頁的功能
- 當收到一個響應時,Requests 會猜測響應的編碼方式,用於在你調用response.text 方法時對響應進行解碼。Requests 首先在 HTTP 頭部檢測是否存在指定的編碼方式,如果不存在,則會使用 chardet.detect來嘗試猜測編碼方式(存在誤差)
- 更推薦使用response.content.deocde()
通過requests獲取網絡上圖片的大小
from io import BytesIO,StringIO
import requests
from PIL import Image
img_url = "http://imglf1.ph.126.net/pWRxzh6FRrG2qVL3JBvrDg==/6630172763234505196.png"
response = requests.get(img_url)
f = BytesIO(response.content)
img = Image.open(f)
print(img.size)
輸出結果:
(500, 262)
理解一下 BytesIO 和StringIO
很多時候,數據讀寫不一定是文件,也可以在內存中讀寫。
StringIO顧名思義就是在內存中讀寫str。
BytesIO 就是在內存中讀寫bytes類型的二進制數據
例子中如果使用StringIO 即f = StringIO(response.text)會產生"cannot identify image file"的錯誤
當然上述例子也可以把圖片存到本地之後再使用Image打開來獲取圖片大小
動手
使用requests爬取任意輸入的百度貼吧的網頁,並保存到本地