Requests模塊是第三方模塊,需要預先安裝,requests模塊在python內置模塊的基礎上進行了高度的封裝,從而使得python進行網絡請求時,變得更加簡潔和人性化。
1.安裝
非常簡單,打開cmd,直接pip安裝,或pycharm 中搜索 requests 安裝即可.
pip install requests
2.導入模塊
import requests
3.簡單使用
Get 請求
發送無參數的get請求,嘗試獲取某個網頁.
r = requests.get('http://www.baidu.com')
發送無參數的get請求 設置超時時間 timeout 單位秒
r = requests.get('http://www.baidu.com', timeout=1)
發送帶參數的請求.
你也許經常想為 URL 的查詢字符串(query string) 傳遞某種數據。如果你是手工構建 URL,那么數據會以鍵/值對的形式置於 URL 中,跟在一個問號的后面。例如, www.baidu.com/?key=val。 Requests 允許你使用 params 關鍵字參數,以一個字符串字典來提供這些參數。舉例來說,如果你想傳遞 key1=value1 和 key2=value2 到 www.baidu.com/ ,那么你可以使用如下代碼:
payload = {'key1': 'value1', 'key2': 'value2'} r = requests.get("https://www.baidu.com/", params=payload) print(r.url) https://www.baidu.com/?key2=value2&key1=value1
你還可以將一個列表作為值傳入.
payload = {'key1': 'value1', 'key2': ['value2', 'value3']} r = requests.get('http://www.baidu.com/', params=payload) print(r.url) http://www.baidu.com/?key2=value2&key2=value3&key1=value1
定制請求頭
如果你想為請求添加 HTTP 頭部,只要簡單地傳遞一個 dict 給 headers 參數就可以了
url = 'https://www.baidu.com/s?wd=python' headers = { 'Content-Type': 'text/html;charset=utf-8', 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' } r = requests.get(url,headers=headers)
Response對象使用.
r.url #打印輸出該 URL r.headers #以字典對象存儲服務器響應頭,但是這個字典比較特殊,字典鍵不區分大小寫,若鍵不存在則返回None r.status_code #返回連接狀態,200正常。 r.text #默認以unicode形式返回網頁內容,也就是網頁源碼的字符串。 r.content #以字節形式(二進制)返回。字節方式的響應體,會自動為你解碼 gzip 和 deflate 壓縮。 r.json() #把網頁中的json數據轉成字典並將其返回。 r.encoding #獲取當前的編碼 r.encoding = 'ISO-8859-1' #指定編碼,r.text返回的數據類型,寫在r.text之前。
POST 請求
HTTP 協議規定 POST 提交的數據必須放在消息主體(entity-body)中,但協議並沒有規定數據必須使用什么編碼方式,服務端通過是根據請求頭中的Content-Type字段來獲知請求中的消息主體是用何種方式進行編碼,再對消息主體進行解析。具體的編碼方式包括:
1.最常見post提交數據的方式,以form表單形式提交數據
application/x-www-form-urlencoded
2.以json串提交數據。
application/json
3.一般使用來上傳文件
multipart/form-data
實例如下:
1. 以form形式發送post請求
Reqeusts支持以form表單形式發送post請求,只需要將請求的參數構造成一個字典,然后傳給requests.post()的data參數即可
payload = {'key1': 'value1', 'key2': 'value2' } r = requests.post("http://httpbin.org/post", data=payload) print(r.text) ... "form": { "key1": "value1", "key2": "value2" }, ...
2. 以json形式發送post請求
可以將一 json串傳給requests.post()的data參數,
url = 'http://httpbin.org/post' payload = {'key1': 'value1', 'key2': 'value2'} r = requests.post(url, data=json.dumps(payload)) #print(r.text) print(r.headers.get('Content-Type')) application/json
3. 以multipart形式發送post請求
Requests也支持以multipart形式發送post請求,只需將一文件傳給requests.post()的files參數即可,文本文件report.txt的內容只有一行:Hello world!,從請求的響應結果可以看到數據已上傳到服務端中。
url = 'http://httpbin.org/post' files = {'file': open('report.txt', 'rb')} r = requests.post(url, files=files) print(r.text) { ... "files": { "file": "hello world" }, "form": {}, "headers": { "Content-Type": "multipart/form-data; boundary=6db46af64e694661985109da21c8fe9b", }, "json": null, "origin": "223.72.217.138", "url": "http://httpbin.org/post" ... }
實例:
1.下載單張圖片並保存到本地磁盤目錄.
#!/usr/bin/env python #coding:utf-8 import requests import os # 下載圖片URL url = 'https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png' # 保存地址 path = "D://圖片//" # 構造下載圖片url down = path + url.split('/')[-1] #print(down) # D://圖片//bd_logo1_31bdc765.png try: # 判斷目錄是否存在 if not os.path.exists(path): os.mkdir(path) # 如果url不存在,則開始下載 if not os.path.exists(down): r = requests.get(url) print(r) # 開始寫文件,wb代表寫二進制文件 with open(down,'wb') as f: # 圖片以二進制形式保存(r.content) f.write(r.content) print("圖片下載成功") else: print("圖片已經存在.") except Exception as e : print("爬取失敗:",str(e))
2.使用requests模塊和bs4模塊,抓取貼吧圖片並保存到指定目錄,這個保存的圖片名稱可能會比較的長,后面會處理.
#!/usr/bin/env python #coding:utf-8 import requests from bs4 import BeautifulSoup import os #圖片保存路徑: path = "D://爬蟲專用//" URL = 'http://tieba.baidu.com/p/1753935195' html_page = requests.get(URL) #創建BeautifulSoup對象 soup = BeautifulSoup(html_page.text,'html.parser') #通過class="BDE_Image"獲取所有的img 標簽 class_image = soup.findAll(attrs={"class":"BDE_Image"}) print(class_image) #判斷目錄是否存在 if not os.path.exists(path): os.mkdir(path) try: # 循環class_image列表,找到所有img標簽的鏈接 for i in class_image: #取出src對應的url地址 src_url = i.get('src') #請求src_url鏈接地址 imge_list = requests.get(src_url) #構造url名稱 down = path + src_url.split('/')[-1] print(down) #以二進制保存圖片 with open(down,'wb') as f: f.write(imge_list.content) except Exception as e: print("pass")
執行后下載圖片如下,文件名太長不美觀,繼續改造.
改造代碼后,圖片的名稱會以1、2、3...的形式存起來.
#!/usr/bin/env python #coding:utf-8 import requests from bs4 import BeautifulSoup import os #圖片保存路徑: path = "D://爬蟲專用//" URL = 'http://tieba.baidu.com/p/1753935195' html_page = requests.get(URL) #創建BeautifulSoup對象 soup = BeautifulSoup(html_page.text,'html.parser') #通過class="BDE_Image"獲取所有的img 標簽 class_image = soup.findAll(attrs={"class":"BDE_Image"}) print(class_image) #判斷目錄是否存在 if not os.path.exists(path): os.mkdir(path) try: x = 0 # 循環class_image列表,找到所有img標簽的鏈接 for i in class_image: #取出src對應的url地址 src_url = i.get('src') #請求src_url鏈接地址 imge_list = requests.get(src_url) #構造url名稱 #down = path + src_url.split('/')[-1] down = path + '%s.jpg' %x print(down) #以二進制保存圖片 with open(down,'wb') as f: f.write(imge_list.content) x += 1 except Exception as e: print("pass")
ok,改造后看看結果.
oye,成功.下次在學習下分頁爬取.
下面,我們來一個牛逼的腳本,爬取www.mzitu.com中所有妹子的圖片,而且涉及到分頁和更復雜的流程控制.這個腳本是我在網上找的然后改動了下,注釋都是我執行后添加的,適合學習和了解.
#!/usr/bin/env python #coding:utf-8 import requests import os from bs4 import BeautifulSoup #訪問的域名地址 all_url = 'http://www.mzitu.com' #配置header 請求頭 headers_w = { 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)', 'Referer': 'http://www.mzitu.com' } headers_i = { 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)', 'Referer': 'http://i.meizitu.net' } #發送get請求,獲取某個網頁,並使用.text屬性打印出源碼信息 start_html = requests.get(all_url,headers=headers_w) #print(start_html.text) #定義保存地址. path = 'D:\\images\\' #尋求最大頁數 #我們使用bs4模塊開從html文件中提取數據,使用BeautifulSoup模塊解析代碼 soup = BeautifulSoup(start_html.text,'html.parser') #print(soup) #找出源碼中所有包含class_='page-numbers'的a標簽,會以一個列表的形式保存 page = soup.find_all('a',class_='page-numbers') #print(page) #取出next的上一個頁面數199 max_page = page[-2].text #print(max_page) # same_url = "http://www.mzitu.com/page/" for i in range(1,int(max_page)+1): #構造每頁的url page_url = same_url + str(i) #print(page_url) #請求每頁的url get_page_url = requests.get(page_url,headers=headers_w) #加載每頁源碼內容 page_soup = BeautifulSoup(get_page_url.text,'html.parser') #print(page_soup) # 將div標簽中包含class_=''postlist取出,在取出a標簽中target=_blank的標簽內容. get_all_a = soup.find('div',class_='postlist').find_all('a',target='_blank') #print(get_all_a) for a in get_all_a: #print(a) #從標簽中獲取所有文字內容 title = a.get_text() #print(title) if title != '': print("准備爬取:%s" %(title)) #處理字符串,先去除空行,然后將?號替換為空,再將':'替換成空行 #判斷目錄是否存在 #print(path + title.strip().replace('?','').replace(':','')) if not os.path.exists(path + title.strip().replace('?','').replace(':','')): os.makedirs(path + title.strip().replace('?','').replace(':','')) # 改變當前工作目錄;相當於shell下cd os.chdir(path + title.strip().replace('?', '').replace(':', '')) # 獲取每一張圖片頁面的url,如http://www.mzitu.com/155568 href = a.get('href') # print(href) # 圖片url中取出圖片的頁數和jpg結尾的圖片地址 html = requests.get(href,) mess = BeautifulSoup(html.text,'html.parser') pic_max = mess.find_all('span') # pic_max[10] 取出來的是圖片頁數,如<span>41</span>、<span>42</span> pic_max = pic_max[10].text #print(pic_max) if len(os.listdir(path+title.strip().replace('?','').replace(':',''))) >= int(pic_max): print('已經保存完畢,跳過') continue for num in range(1,int(pic_max)+1): #print(num) pic = href + '/' + str(num) # 打印出url如下:http://www.mzitu.com/155192/44 #print(pic) #從pic的url中取出圖片地址 html = requests.get(pic,headers=headers_w) #print(html.url) mess = BeautifulSoup(html.text,'html.parser') #print(mess) pic_url = mess.find('img', alt=title) #打印出圖片地址: <img alt="外拍精彩呈現" src="http://i.meizitu.net/2018/11/01a02.jpg"/> #print(pic_url) html_img = requests.get(pic_url.get('src'),headers=headers_i) #請求每張圖片的下載url:http://i.meizitu.net/2018/11/02f33.jpg #print(html_img.url) file_name = pic_url.get('src').split('/')[-1] #print(file_name) with open(file_name,'wb') as f : f.write(html_img.content) print('圖片 %s 保存完成' %(file_name)) print('第',i,'頁爬取完成.')
執行后就這樣爬下了所以美眉的圖片,是不是特別有學習的動力呢.
參考文檔: http://docs.python-requests.org/zh_CN/latest/user/quickstart.html
https://www.jb51.net/article/133660.htm
https://blog.csdn.net/qq_878799579/article/details/73956344?utm_source=blogxgwz0