本文同步發表於個人微信公衆號,掃一掃文章底部的二維碼或在微信搜索 極客導航 便可關注,每一個工做日都有文章更新。html
網絡請求多是每門語言比較重要的一部分了,在Python語言中,雖然有urllib
這樣的自帶原生網絡請求庫,可是它的一些API對待開發者好像不怎麼友好。So,Requests
的革命開始了,不只API人性化,更重要的是它支持urllib
全部特性。python
Requests
支持HTTP鏈接保持和鏈接池,支持使用cookie保持會話,支持文件上傳,支持自動肯定響應內容的編碼,支持國際化的URL
和 POST
數據自動編碼。好處很少說了,咱們快來體驗一下吧。json
好像忘記說了一句,Requests的庫再牛逼,底層也是urllib
。 bash
pip3 install requests
複製代碼
###3、使用服務器
response = requests.get("http://www.baidu.com/")
複製代碼
看到沒,對,你沒看錯,發起GET請求就短短的一行代碼。 返回的response
有不少屬性,咱們來看看:微信
response.text 返回解碼後的字符串,
respones.content 以字節形式(二進制)返回。
response.status_code  響應狀態碼
response.request.headers  請求的請求頭
response.headers  響應頭
response.encoding = 'utf-8' 能夠設置編碼類型
response.encoding 獲取當前的編碼
response.json() 內置的JSON解碼器,以json形式返回,前提返回的內容確保是json格式的,否則解析出錯會拋異常
複製代碼
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)
複製代碼
返回的內容以下:cookie
......內容太多,不宜展現
......內容太多,不宜展現
'http://www.baidu.com/s?wd=%E9%95%BF%E5%9F%8E'
'utf-8'
200
複製代碼
注意網絡
response.text
時,Requests
會基於 HTTP 響應的文本編碼自動解碼響應內容,大多數 Unicode 字符集都能被無縫地解碼。response.content
時,返回的是服務器響應數據的原始二進制字節流,能夠用來保存圖片等二進制文件。好比:app
import requests
response = requests.get("http://www.sina.com")
print(response.request.headers)
print(response.content.decode('utf-8'))
複製代碼
結果:svg
<!DOCTYPE html>
<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,新浪首頁,門戶,資訊" />
...
複製代碼
若是用response.text
可能會出現亂碼狀況,好比:
import requests
response = requests.get("http://www.sina.com")
print(response.text)
複製代碼
結果:
<!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
會猜想響應的編碼方式,用於在你調用response.text
方法時對響應進行解碼。Requests
首先在 HTTP 頭部檢測是否存在指定的編碼方式,若是不存在,則會使用 chardet.detect
來嘗試猜想編碼方式(存在偏差),因此更推薦 response.content.deocde()
網站登陸和註冊等功能通常都是經過post請求方式作的,學會用Requests
發起post請求也是爬取須要登陸網站的第一步。
import requests
#測試請求地址
req_url = "https://httpbin.org/post"
#表單數據
formdata = {
'username': 'test',
'password': '123456',
}
#添加請求頭
req_header = {
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
}
#發起請求
response = requests.post(
req_url,
data = formdata,
headers = req_header
)
print (response.text)
# 若是是json文件能夠直接顯示
#print (response.json())
複製代碼
結果:
{
"args": {},
"data": "",
"files": {},
"form": {
"password": "123456",
"username": "test"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "29",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
},
"json": null,
"origin": "223.72.76.90, 223.72.76.90",
"url": "https://httpbin.org/post"
}
複製代碼
url = 'https://httpbin.org/post'
files = {'file': open('image.png', 'rb')}
response = requests.post(url, files=files)
print(response.text)
複製代碼
結果:
{
"args": {},
"data": "",
"files": {
"file": "....內容太多,不宜展現"
},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "27597",
"Content-Type": "multipart/form-data; boundary=16afeeccbaec949570677ca271dc2d0c",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.21.0"
},
"json": null,
"origin": "223.72.76.90, 223.72.76.90",
"url": "https://httpbin.org/post"
}
複製代碼
以上是Requests
最基本的Get請求和Post請求,語法比較簡單,這也是學會爬蟲的第一步。加油吧!騷年。
歡迎關注個人公衆號,咱們一塊兒學習。