近期在MOOC上通過看北京理工大學嵩天老師的Python課程學習網絡爬蟲,對Requests庫內容進行如下總結。
一、主要方法
方法 | 說明 |
requests.request() | 構造一個請求,支撐以下各方法的基礎方法 |
requests.get() | 獲取HTML網頁的主要方法,對應於HTTP的GET |
requests.head() | 獲取HTML網頁頭部信息的方法,對應於HTTP的HEAD |
requests.post() | 向HTML網頁提交POST請求的方法,對應於HTTP的POST |
requests.put() | 向HTML網頁提交PUT請求的方法,對應於HTTP的PUT |
requests.patch() | 向HTML網頁提交局部修改請求,對應於HTTP的PATCH |
requests.delete() | 向HTML頁面提交刪除請求,對應於HTTP的DELETE |
1、request方法
requests.request(method,url,**kwargs)
method:請求方式,有‘GET’‘HEAD’‘POST’‘PUT’‘PATCH’‘delete’‘OPTIONS’等7種
url:擬獲取頁面的url鏈接
**kwargs:控制訪問的參數,共13個
參數 | 說明 |
params | 字典或字節序列,作為參數增加到url中 |
data | 字典、字節序列或文件對象,作為Request的內容 |
json | JSON格式的數據,作為Request的內容 |
headers | 字典,HTTP定制頭 |
cookies | 字典或CookieJar,Request中的cookie |
auth | 元組,支持HTTP認證功能 |
files | 字典類型,傳輸文件 |
timeout | 設定超時時間,秒為單位 |
proxies | 字典類型,設定訪問代理服務器,可以增加登錄認證 |
allow_redirects | True/False,默認為True,重定向開關 |
stream | True/False,默認為True,獲取內容立即下載開關 |
verify | True/False,默認為True,認證SSL證書開關 |
cert | 本地SSL證書路徑 |
2、get方法
requests.get(url,params = None,**kwargs)
url:擬獲取頁面的url鏈接
params:url中的額外參數,字典或字節流格式(可選)
**kwargs:12個控制訪問的參數(與request方法相比少了一個proxies參數)
1 r = requests.get(url)
get方法構造一個向服務器請求資源的Ruquest對象,返回一個包含服務器資源的Response對象
Response對象的常用屬性
屬性 | 說明 |
r.status_code | HTTP請求的返回狀態,200表示連接成功,404表示失敗 |
r.text | HTTP相應內容的字符串狀態,即url對應的頁面內容 |
r.encoding | 從HTTP header中猜測的響應內容編碼方式(如果header中不存在charset,則認為編碼為ISO-8859-1) |
r.apparent_encoding | 從內容中分析出的響應內容編碼方式(備選編碼方式) |
r.content | HTTP響應內容的二進制形式 |
1 r = requests.get("http://www.baidu.com") 2 print(r.status_code) 3 200 4 type(r) 5 <class 'requests.models.Response'> 6 r.headers 7 {'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Sun, 01 Mar 2020 09:29:13 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:27:56 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}
1:利用get方法獲取Response對象(賦值給r)
2:打印HTTP請求返回狀態
3:HTTP返回狀態
4:檢測r的類型
5:r的類型
6:查看r的頭部信息
7:r的頭部信息
理解Response的編碼
1 r = requests.get("http://www.baidu.com") 2 r.text 3 '<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>ç\x99¾åº¦ä¸\x80ä¸\x8bï¼\x8cä½\xa0å°±ç\x9f¥é\x81\x93</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=ç\x99¾åº¦ä¸\x80ä¸\x8b class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ\x96°é\x97»</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>å\x9c°å\x9b¾</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>è§\x86é¢\x91</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>è´´å\x90§</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>ç\x99»å½\x95</a> </noscript> <script>document.write(\'<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=\'+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ \'" name="tj_login" class="lb">ç\x99»å½\x95</a>\');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">æ\x9b´å¤\x9a产å\x93\x81</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>å\x85³äº\x8eç\x99¾åº¦</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>使ç\x94¨ç\x99¾åº¦å\x89\x8då¿\x85读</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>æ\x84\x8fè§\x81å\x8f\x8dé¦\x88</a> 京ICPè¯\x81030173å\x8f· <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n' 4 r.encoding 5 'ISO-8859-1' 6 r.apparent_encoding 7 'utf-8' 8 r.encoding = r.apparent_encoding 9 r.text 10 '<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新聞</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地圖</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>視頻</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>貼吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登錄</a> </noscript> <script>document.write(\'<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=\'+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ \'" name="tj_login" class="lb">登錄</a>\');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多產品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>關於百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>©2017 Baidu <a href=http://www.baidu.com/duty/>使用百度前必讀</a> <a href=http://jianyi.baidu.com/ class=cp-feedback>意見反饋</a> 京ICP證030173號 <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'
r的header中不存在charset,encoding默認編碼為“ISO-8859-1”。將apparent_encoding(由r的內容得出編碼方式)賦值給encoding,獲得正確的編碼。
3、head方法
requests.head(url,**kwargs)
url:擬獲取頁面的url鏈接
**kwargs:控制訪問的參數,共13個(與request方法參數完全一樣)
4、post方法
requests.post(url,data = None,json = None,**kwargs)
url:擬獲取頁面的url鏈接
data:字典、字節序列或文件,Request的內容
json:JSON格式的數據,Request的內容
**kwargs:控制訪問的參數,共11個
5、put方法
requests.put(url,data = None,**kwargs)
url:擬獲取頁面的url鏈接
data:字典、字節序列或文件,Request的內容
**kwargs:控制訪問的參數,共12個
6、patch方法
requests.patch(url,data = None,**kwargs)
url:擬獲取頁面的url鏈接
data:字典、字節序列或文件,Request的內容
**kwargs:控制訪問的參數,共12個
7、delete方法
requests.delete(url,**kwargs)
url:擬獲取頁面的url鏈接
**kwargs:控制訪問的參數,共13個(與request方法參數完全一樣)
二、網頁爬取
1、HTTP
HTTP,Hypertext Transfer Protocol,超文本傳輸協議。HTTP是一個基於“請求與響應”模式的、無狀態的應用層協議,采用URL作為定位網絡資源的標識。URL是通過HTTP協議存取資源的Internet路徑,一個URL對應一個數據資源。
URL格式: http://host[:port][path]
host:合法的Internet主機域名或IP地址
port:端口號,缺省端口為80
path:請求資源的路徑
HTTP協議對資源的操作
方法 | 說明 |
GET | 請求獲取URL位置的資源 |
HEAD | 請求獲取URL位置資源的響應消息報告,即獲取該資源的頭部信息 |
POST | 請求向URL位置的資源后附加新的數據 |
PUT | 請求向URL位置存儲一個資源,覆蓋原URL位置的資源 |
PATCH | 請求局部更新URL位置的資源,即改變該處資源的部分內容 |
DELETE | 請求刪除URL位置存儲的資源 |
2、異常
異常 | 說明 |
requests.ConnectionError | 網絡連接錯誤異常,如DNS查詢失敗、拒絕連接等 |
requests.HTTPError | HTTP錯誤異常 |
requests.URLRequired | URL缺失異常 |
requests.TooManyRedirects | 超過最大重定向次數,產生重定向異常 |
requests.ConnectTimeout | 連接遠程服務器超時異常 |
requests.Timeout | 請求URL超時,產生超時異常 |
r.raise_for_status() | 如果不是200,產生異常requests.HTTPError |
3、爬取網頁通用代碼框架
1 try: 2 r = requests.get(url,timeout = 30) 3 r.raise_for_status() #如果狀態不是200,引發HTTPError異常 4 r.encoding = r.apparent_encoding 5 return r.text 6 except: 7 return "產生異常"
三、實例
1、京東商品頁面的爬取
1 r = requests.get("https://item.jd.com/100008348542.html") 2 r.status_code 3 200 4 r.text[:1000] #前1000個字符 5 '<!DOCTYPE HTML>\n<html lang="zh-CN">\n<head>\n <!-- shouji -->\n <meta http-equiv="Content-Type" content="text/html; charset=gbk" />\n <title>【AppleiPhone 11】Apple iPhone 11 (A2223) 128GB 黑色 移動聯通電信4G手機 雙卡雙待【行情 報價 價格 評測】-京東</title>\n <meta name="keywords" content="AppleiPhone 11,AppleiPhone 11,AppleiPhone 11報價,AppleiPhone 11報價"/>\n <meta name="description" content="【AppleiPhone 11】京東JD.COM提供AppleiPhone 11正品行貨,並包括AppleiPhone 11網購指南,以及AppleiPhone 11圖片、iPhone 11參數、iPhone 11評論、iPhone 11心得、iPhone 11技巧等信息,網購AppleiPhone 11上京東,放心又輕松" />\n <meta name="format-detection" content="telephone=no">\n <meta http-equiv="mobile-agent" content="format=xhtml; url=//item.m.jd.com/product/100008348542.html">\n <meta http-equiv="mobile-agent" content="format=html5; url=//item.m.jd.com/product/100008348542.html">\n <meta http-equiv="X-UA-Compatible" content="IE=Edge">\n <link rel="canonical" href="//item.jd.com/100008348542.html"/>\n <link rel="dns-prefetch" href="//misc.360buyimg.com"/'
該例子直接爬取網站數據,查看返回狀態正常,然后輸出。
京東商品頁面爬取全代碼
1 import requests 2 url = "https://item.jd.com/100008348542.html" 3 try: 4 r = requests.get(url) 5 r.raise_for_status() 6 r.encoding = r.apparent_encoding 7 print(r.text[:1000] #前1000個字符 8 except: 9 print("爬取失敗")
2、亞馬遜商品頁面的爬取
1 import requests 2 r = requests.get("https://www.amazon.cn/dp/B01N5RGXYR/ref=Oct_DLandingS_rdp_db4d4b3c") 3 r.status_code 4 503 5 r.encoding 6 'ISO-8859-1' 7 r.apparent_encoding 8 'utf-8' 9 r.encoding = r.apparent_encoding 10 r.text[2000:3000] #第2001到第3000個字符 11 ' <i class="a-icon a-icon-alert"></i>\n <h4>請輸入您在下方看到的字符</h4>\n <p class="a-last">抱歉,我們只是想確認一下當前訪問者並非自動程序。為了達到最佳效果,請確保您瀏覽器上的 Cookie 已啟用。</p>\n </div>\n </div>\n\n <div class="a-section">\n\n <div class="a-box a-color-offset-background">\n <div class="a-box-inner a-padding-extra-large">\n\n <form method="get" action="/errors/validateCaptcha" name="">\n <input type=hidden name="amzn" value="Gkp1fR4D0RV74ajxxWv5/A==" /><input type=hidden name="amzn-r" value="/dp/B01N5RGXYR/ref=Oct_DLandingS_rdp_db4d4b3c" />\n <div class="a-row a-spacing-large">\n <div class="a-box">\n <div class="a-box-inner">\n <h4>請輸入您在這個圖片中看到的字符:</h4>\n <div class="a-row a-text-center">\n ' 12 r.request.headers 13 {'User-Agent': 'python-requests/2.23.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} 14 kv = {'user-agent':'Mozilla/5.0'} 15 url = "https://www.amazon.cn/dp/B01N5RGXYR/ref=Oct_DLandingS_rdp_db4d4b3c" 16 r = requests.get(url,headers = kv) 17 r.status_code 18 200 19 r.request.headers 20 {'user-agent': 'Mozilla/5.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'} 21 r.text[2000:3000] #第2001到第3000個字符 22 ' <i class="a-icon a-icon-alert"></i>\n <h4>请è¾\x93å\x85¥æ\x82¨å\x9c¨ä¸\x8bæ\x96¹ç\x9c\x8bå\x88°ç\x9a\x84å\xad\x97符</h4>\n <p class="a-last">æ\x8a±æ\xad\x89ï¼\x8cæ\x88\x91们å\x8fªæ\x98¯æ\x83³ç¡®è®¤ä¸\x80ä¸\x8bå½\x93å\x89\x8d访é\x97®è\x80\x85å¹¶é\x9d\x9eè\x87ªå\x8a¨ç¨\x8båº\x8fã\x80\x82为äº\x86è¾¾å\x88°æ\x9c\x80ä½³æ\x95\x88æ\x9e\x9cï¼\x8c请确ä¿\x9dæ\x82¨æµ\x8fè§\x88å\x99¨ä¸\x8aç\x9a\x84 Cookie å·²å\x90¯ç\x94¨ã\x80\x82</p>\n </div>\n </div>\n\n <div class="a-section">\n\n <div class="a-box a-color-offset-background">\n <div class="a-box-inner a-padding-extra-large">\n\n <form method="get" action="/errors/validateCaptcha" name="">\n <input type=hidden name="amzn" value="9HvqB4kIQY6TxIwPw1QJ4w==" /><input type=hidden name="amzn-r" value="/dp/B01N5RGXYR/ref=Oct_DLandingS_rdp_db4d4b3c" />\n <div class="a-row a-spacing-large">\n <div class="a-box">\n <div class="a-box-inner">\n '
該例子爬取網站數據后發現返回狀態錯誤,因為該網站拒絕爬蟲訪問,在request請求中將'user-agent'的值由'python-requests/2.23.0'改為'Mozilla/5.0',即爬蟲訪問改為瀏覽器訪問(模擬瀏覽器訪問),然后訪問成功。
亞馬遜商品頁面爬取全代碼
1 import requests 2 url = "https://www.amazon.cn/dp/B01N5RGXYR/ref=Oct_DLandingS_rdp_db4d4b3c" 3 try: 4 kv = {'user-agent':'Mozilla/5.0'} 5 r = requests.get(url,headers = kv) 6 r.raise_for_status() 7 r.encoding = r.apparent_encoding 8 print(r.text[1000:2000] #第1001到第2000個字符 9 except: 10 print("爬取失敗")
3、百度360搜索關鍵詞提交
百度的關鍵詞接口
http://www.baidu.com/s?wd=keyword
1 import requests 2 kv = {'wd':'Python'} 3 r = requests.get("http://www.baidu.com/s",params = kv) 4 r.status_code 5 200 6 r.request.url 7 'https://wappass.baidu.com/static/captcha/tuxing.html?&ak=c27bbc89afca0463650ac9bde68ebe06&backurl=https%3A%2F%2Fwww.baidu.com%2Fs%3Fwd%3DPython&logid=11418784497796902027&signature=de72d4c97890b2a959f599c9dec04cb7×tamp=1583078733' 8 len(r.text) 9 1519
百度關鍵詞查詢全代碼
1 import requests 2 keyword = "Python" 3 try: 4 kv = {'wd':keyword} 5 r = requests.get("http://www.baidu.com/s",params = kv) 6 print(r.request.url) 7 r.raise_for_status() 8 print(len(r.text)) 9 except: 10 print("爬取失敗")
360的關鍵詞接口
1 import requests 2 kv = {'q':'Python'} 3 r = requests.get("http://www.so.com/s",params = kv) 4 r.status_code 5 200 6 r.request.url 7 'https://www.so.com/s?q=Python' 8 len(r.text) 9 384244
360關鍵詞查詢全代碼
1 import requests 2 keyword = "Python" 3 try: 4 kv = {'q':keyword} 5 r = requests.get("http://www.so.com/s",params = kv) 6 print(r.request.url) 7 r.raise_for_status() 8 print(len(r.text)) 9 except: 10 print("爬取失敗")
以上兩例子根據接口賦值即可。
4、網絡圖片的爬取
網絡圖片鏈接的格式
http://www.example.com/picture.jpg
1 import requests 2 path = "D:/abc.jpg" 3 url ="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583091303697&di=888f5e536474f93b599cc53ba4fa91c4&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn14%2F569%2Fw640h729%2F20180505%2Fee80-hacuuvt5406878.jpg" 4 r = requests.get(url) 5 r.status_code 6 200 7 with open(path,'wb') as f: 8 f.write(r.content) 9 f.close()
網絡圖片爬取全代碼
1 import requests 2 import os 3 url = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583091303697&di=888f5e536474f93b599cc53ba4fa91c4&imgtype=0&src=http%3A%2F%2Fn.sinaimg.cn%2Fsinacn14%2F569%2Fw640h729%2F20180505%2Fee80-hacuuvt5406878.jpg" 4 root = "D://picture//" 5 path = root + url.split('/')[-1] 6 try: 7 if not os.path.exists(root): 8 os.mkdir(root) 9 if not os.path.exists(path): 10 r = requests.get(url) 11 with open(path,'wb') as f: 12 f.write(r.content) 13 f.close() 14 print("文件保存成功") 15 else: 16 print("文件已存在") 17 except: 18 print("爬取失敗")
5、ID地址歸屬地的自動查詢
126查詢接口:http://ip.ws.126.net/ipquery?ip=ipaddress
1 import requests 2 url = 'http://ip.ws.126.net/ipquery?ip=' 3 r = requests.get(url + '123.123.123.123') 4 r.status_code 5 200 6 r.text 7 'var lo="北京市", lc="北京市";\r\nvar localAddress={city:"北京市", province:"北京市"}\r\n'
IP地址查詢全代碼
1 import requests 2 url = 'http://ip.ws.126.net/ipquery?ip=' 3 try: 4 r = requests.get(url + '123.123.123.123') 5 r.raise_for_status() 6 r.encoding = r.apparent_encoding 7 print(r.text[-500:]) 8 except: 9 print("爬取失敗")
資料來源:《Python網絡爬蟲與信息提取》——嵩天,北京理工大學,MOOC