python3網路爬蟲學習——使用requests(1)

來源:互聯網
上載者:User

標籤:亂碼   表徵圖   let   讀寫檔案   rgs   length   org   image   agent   

reuqests庫中有很多便捷的方法,比如以GET方式獲得網頁,在requests庫中就是方法get(),上代碼

import requestsr = requests.get(‘https://www.baidu.com‘)print(type(r))print(r.status_code)print(type(r.text))print(r.text)print(r.cookies)

相當於urlopen的方法,得到一個Response對象,然後分別輸出他的類型,狀態代碼,相應體的類型,內容以及Cookies

requests還有許多的方法比如post,put,delete,head,options等分別表示其請求

由於HTTP中最常見的就是GET請求,因此下面用其來構建一個GET請求執行個體:

  • 基本執行個體
import requestsdata = {        ‘name‘:‘germey‘,        ‘age‘:‘22‘        }#也可以不用建立data字典,直接把網址後面加上“?name=germey&age=22"但這樣明顯麻煩很多r = requests.get(‘http://httpbin.org/get‘,params = data)print(r.text)#網頁返回的是str類型,JSON格式的,我們可以用json方法將JSON格式的字串轉化為字典
print(r.json())runfile(‘F:/Python/exercise/pygame/untitled0.py‘, wdir=‘F:/Python/exercise/pygame‘){ "args": { "age": "22", "name": "germey" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Host": "httpbin.org", "User-Agent": "python-requests/2.18.4" }, "origin": "182.108.3.27", "url": "http://httpbin.org/get?name=germey&age=22"}{‘args‘: {‘age‘: ‘22‘, ‘name‘: ‘germey‘}, ‘headers‘: {‘Accept‘: ‘*/*‘, ‘Accept-Encoding‘: ‘gzip, deflate‘, ‘Connection‘: ‘close‘, ‘Host‘: ‘httpbin.org‘, ‘User-Agent‘: ‘python-requests/2.18.4‘}, ‘origin‘: ‘182.108.3.27‘, ‘url‘: ‘http://httpbin.org/get?name=germey&age=22‘}

但要注意的是如果不是JSON格式便會出現解析錯誤json.decoder.JSONDecodeError錯誤

  • 抓取位元據

在抓取網頁中,我們抓取的是一個頁面,也就是一個HTML檔案,如果想抓取圖片,音頻,視頻等檔案,則需要抓取他們的二進位檔案,再將它們解碼得到

import requestsr = requests.get("https://github.com/favicon.ico")print(r.text)print(r.content)

開啟後我們是這樣的

 

 可以看出其有兩個屬性,一個是text屬性,其為Unicode類型的檔案,也就是符號集類型,其中英文字母其還是為英文,但中文字元就會表示為亂碼的形式,一個為content屬性,其為二進位形式的類型,開頭有一個b表示其檔案類型

再添加代碼開啟檔案

with open(‘facicon.ico‘,‘wb‘) as f:    f.write(r.content)

其中open函數的第一個參數為圖片名稱,第二個參數為以二進位方式開啟,然後就會發現在當前檔案夾下儲存了一個名為favicon.ico的表徵圖

不過這裡我有一點疑惑,為何不是儲存為一個包含這些二進位代碼的txt文字檔,我猜測是因為,在讀寫檔案的時候,電腦現將這個二進位編碼進行轉換,轉得到的檔案類型為ico則存為ico,為字串則存為txt,那麼應該在這個二進位檔案裡包含了儲存為何種類型檔案的資訊

有的時候,有些網站可能禁止我們訪問,這個時候加上User-agent就可以了,只要在requests.get(‘url‘,headers=‘   ‘)就可以了

2.post請求

import requestsdata = {‘name‘:‘germy‘,‘age‘:‘22‘}r = requests.post("https://httpbin.org/post",data=data)print(r.text)print(r.content)

{
"args": {},
"data": "",
"files": {},
"form": {
"age": "22",
"name": "germy"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "17",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.4"
},
"json": null,
"origin": "218.64.33.30",
"url": "https://httpbin.org/post"
}

b‘{\n "args": {}, \n "data": "", \n "files": {}, \n "form": {\n "age": "22", \n "name": "germy"\n }, \n "headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", \n "Connection": "close", \n "Content-Length": "17", \n "Content-Type": "application/x-www-form-urlencoded", \n "Host": "httpbin.org", \n "User-Agent": "python-requests/2.18.4"\n }, \n "json": null, \n "origin": "218.64.33.30", \n "url": "https://httpbin.org/post"\n}\n‘

可以得到返回結果,其中form就是提交的資料,這就證明POST請求提交成功了

可以通過requests.status_code得到狀態代碼,此外還有history,url,cookies,headers等屬性

import requestsr = requests.get("http://www.jianshu.com")exit() if  r.status_code == requests.codes.ok else print("Request Successfully")

顯示為Request Successfully

當然requests.codes有ok這個條件碼,我們用這個條件碼可以得到相應的狀態代碼200,當然我們可不止這一個條件碼,還有很多

 

python3網路爬蟲學習——使用requests(1)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.