1. 程式人生 > >Python爬蟲_Requests

Python爬蟲_Requests

文章目錄

發出請求

首先匯入Requests模組

import requests

現在,我們嘗試獲取一個網頁

r = requests.get(‘https://api.github.com/events’)

現在,我們有一個名為 r 的 Requests 的物件。我們可以從這個物件獲取我們需要的所有資訊

接下來演示一下POST請求方式:

postdata = {‘key’ : ‘value’}
r = requests.post(‘https://passport.csdn.net/account/login’, data = postdata)

在URL中傳遞引數
你可能見過類似這樣的URL:http://hhh2333.com/get?key=val&key2=val2,就是在網站後面緊跟著“?”,“?”後面還有引數。那麼這樣的GET請求在requests中可以這樣寫:

payloda = {“key1” : “value1”, “key2” : “value2”}
r = requests.get(“

https://blog.csdn.net/UserPython”, params = payload)

你可以通過列印URL看到URL已經正確編碼,問號自動新增

pirnt(r.url)
//https://blog.csdn.net/UserPython?hhh=2333&HHH=3332

import requests

payload = {"hhh" : "2333", "HHH" : "3332"}

r = requests.get("https://blog.csdn.net/UserPython", params = payload)

print(r.url)
""" result: https://blog.csdn.net/UserPython?hhh=2333&HHH=3332 """

響應內容

文字形式響應內容

import requests
r = requests.get(‘http://www.baidu.com’)
print(r.text)

其中r.text返回的是文字形式,當發出請求時,Requests會根據HTTP標頭猜測網頁編碼格式進而解析文字。如果解析文字出現亂碼,可以通過r.encoding檢視使用什麼編碼格式解析,並進行更改

print(r.encoding)
// result:ISO-8859-1
r.encoding = "utf-8"

import requests

r = requests.get("http://www.baidu.com")

# 檢視Requests使用什麼編碼格式解碼,r.encoding返回的是根據HTTP頭猜測的網頁編碼格式
print(r.encoding)
"""
result: ISO-8859-1
"""

# 自行檢視源網頁的編碼格式為UTF-8所以要更改
r.encoding = "utf-8"

print(r.text)
"""
更正後,爬取的HTML網頁沒有亂碼
"""

這種手動的方式略顯笨拙,下面提供一種更加簡便的方式:chardet,這是一個字串/檔案編碼檢測模組,使用chardet.detect()返回字典,其中encoding是源網頁的編碼格式,confidence是檢測精確度,示例如下:

import requests
import chardet

r = requests.get("http://www.baidu.com")

print(chardet.detect(r.content))
{'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}

r.encoding = chardet.detect(r.content)["encoding"]

print(r.text)

二進位制響應內容

對於非文字請求,還可以以位元組為單位訪問響應正文

print(r.content)
//返回二進位制內容

響應狀態碼

檢視響應狀態碼

r = requests.get(“http://www.baidu.com”)
print(r.status_code)
//200

請求還附帶內建狀態碼查詢物件,以便於參考:

print(requests.codes.ok)
//200

import requests

r = requests.get("http://www.baidu.com")

if r.status_code == requests.codes.ok:
    # 獲取響應碼
    print(r.status_code)
    # 獲取響應頭
    print(r.headers)
    # 獲取響應頭中某個欄位,推薦使用這種方式
    print(r.headers.get("content-type"))
    print(r.headers["content-type"]) # 不推薦使用
else:
    r.raise_for_status()

上述程式中,r.headers包含所有的響應頭資訊,可以通過get函式獲取其中的某一個欄位,也可以通過字典引用的方式獲取字典值,但是不推薦,因為如果欄位中沒有這個欄位,第二種方式會丟擲異常,第一種方式會返回None。r.raise_for_status()是用來主動地產生一個異常,當響應碼是4xx或5xx時,raise_for_status()函式會丟擲異常,而響應碼為200時,raise_for_status()函式返回None

請求頭headers處理

在Requests的get函式中新增headers引數即可,如下所示:

import requests

user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/69.0.3497.100"

headers = {"User_Agent" : user_agent}

r = requests.get("http://www.baidu.com", headers = headers)

print(r.content.decode("utf-8"))

Cookie處理

如果響應中包含Cookie的值,可以如下方式獲取Cookie欄位的值

import requests

user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 "

headers = {"User_Agent" : "user_agent"}

r = requests.get("http://www.baidu.com", headers)

# 遍歷出所有cookie欄位的值
for cookie in r.cookies.keys():
    print(cookie + ":" + r.cookies.get(cookie))

自動處理Cookie

希望每次訪問時,程式自動把Cookie的值帶上,像瀏覽器一樣。Requests提供了一個session的概念,在連續訪問網頁,處理登入跳轉時特別方便,不需要關注具體細節

import requests

loginUrl = "http://www.hhh.com/login"

s = requests.Session()

#首先訪問登入介面,作為遊客,伺服器會先分配一個cookie
r = s.get(loginUrl, allow_redirects = True)

datas = {"name" : "UserH", "passwd" : "UserH"}

# 向登入連線傳送POST請求,驗證成功,遊客許可權轉為會員許可權

r = s.post(loginUrl, data = datas, allow_redirects = True)

print(r.text)

上述程式,如果沒有第一步訪問登入的頁面,而是直接向登入連結傳送POST請求,系統會把你當做非法使用者,因為訪問登入介面時會分配一個cookie,需要將這個cookie在傳送POST請求時帶上,這種使用session函式處理Cookie的方式之後會很常用。

重定向與歷史資訊

重定向(Redirect)就是通過各種方法將各種網路請求重新定個方向轉到其它位置。重定向是網頁製作中的一個知識,如:你現在所處的位置是一個論壇的登入頁面,你填寫了賬號,密碼,點選登入,如果你的賬號密碼正確,就自動跳轉到論壇的首頁,不正確就返回登入頁;這裡的自動跳轉,就是重定向的意思。或者可以說,重定向就是在網頁上設定一個約束條件,條件滿足,就自動轉入到其他網頁、網址

處理重定向只是需要設定一下allow_redirects欄位即可,例如r = requests.get(“http://www.baidu.com”, allow_redirects = True)。將allow_redirects設定為True,則是允許重定向;設定為False,則是禁止重定向,如果是允許重定向,可以通過r.history欄位檢視歷史資訊,即可訪問成功之前的所有請求跳轉資訊

import requests

r = requests.get('http://github.com', allow_redirects=True)

print(r.url)
# // https://github.com/

print(r.status_code)
# // 200

print(r.history)
# // [<Response [301]>]

上面的示例程式碼顯示的效果是訪問GitHub網址時,會將所有的HTTP請求全部重定向到HTTPS

超時設定

超時選項是通過引數timeout來進行設定的。可以通過引數timeout告知請求在給定秒數後停止等待響應。幾乎所有生產程式碼都應該在幾乎所有請求中使用此引數。如果不這樣做可能會導致程式無限期掛起。

requests.get( “http://github.com”, timeout = 2)