python爬蟲下載庫:requests庫的安裝和具體用法實例介紹

安裝模塊:

pip install requests

python requests 第三方庫有什麼用?

相對於Python 的標準庫 urllib 下載器來說,requests 下載器使用起來容易理解,也容易開發,這無疑提高了開發的效率。

下面從五個方面講解 requests 庫常見的用法:

ps:文章來源於小編的頭條號:“python數據科學頻道”,想在手機端方便看文章的朋友可以去關注我的頭條號。

1.沒有添加任何參數的情況下

import requests

reponse=requests.get("https://www.baidu.com/")
reponse.encoding='utf-8'
# 返回狀態碼
print(reponse.status_code)
# 打印網頁的內容
print(reponse.text)

2.請求頭

爲什麼要設置請求頭呢?因爲網站爲了防止別人惡意爬取網址的信息而設置的反爬蟲技術。

例如以下例子的爬取https://www.whatismyip.com/網址遭到拒接。

import requests
reponse=requests.get("https://www.whatismyip.com/")
reponse.encoding='utf-8'
# 返回狀態碼
print(reponse.status_code)
# 打印網頁的內容
print(reponse.text)

返回結果是:

 403
 <html>
 <head><title>403 Forbidden</title></head>
 <body bgcolor="white">
 <center><h1>403 Forbidden</h1></center>
 <hr><center>nginx</center>
 </body>
 </html>

所以我們要設置請求頭

import requests

#構建請求頭,模擬瀏覽器訪問
header={'User-Agent': 'Mozilla/5.0 '}
reponse=requests.get('https://www.whatismyip.com/',headers=header)
print(reponse.content.decode('utf-8'))  # 解碼以字符串形式輸出

現在就運行成功了

3.post請求

爲什麼要設置post請求呢?因爲有些網址需要登錄才能訪問,

所以我們要設置post請求的表單信息

import requests
#包裝要發送的數據
data={ 'name':'zhang',  'age':'18' }
header={ 'User-Agent':  'Mozilla/5.0 '}
#調用post()方法進行post請求
reponse=requests.post('http://httpbin.org/post',data=data, headers=header)
# 輸出請求的內容
print(reponse.text)

4.代理的使用

爲什麼要使用代理服務器呢?有時候我們發現以前可以訪問的網站,

現在訪問不了,這是因爲我們的ip被屏蔽了

國內代理服務器網址:http://yum.iqianyue.com/proxy

import requests
proxy = {'http://': '61.135.217.7:80'}
reponse=requests.get('http://www.baidu.com/',proxies=proxy)
# 輸出狀態碼
print(reponse.status_code)

5.超時設置

如果程序長時間沒有響應,我們就需要來設置時間來檢測程序是不是已經超時了(注意時間不要設置太短,要根據網絡、服務器快慢狀態來設置)

import requests
from requests.exceptions import Timeout

try:
	 for i in range(1,51):
  		 reponse=requests.get('http://www.baidu.com/',timeout=3)
  		 print(reponse.status_code)
  
# 一有錯誤就終止程序的運行,輸出錯誤信息
except Timeout as e:
	print(e)

------------------------------------ 文章到此結束 -------------------------------------------------

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章