1. 程式人生 > >Python 爬蟲基礎Requests庫的使用(二十一)

Python 爬蟲基礎Requests庫的使用(二十一)

(一)人性化的Requests庫

在Python爬蟲開發中最為常用的庫就是使用Requests實現HTTP請求,因為Requests實現HTTP請求簡單、操作更為人性化。

(二)get請求的基本用法

  1. def get(url, params=None, **kwargs)

get()函式:

引數 說明
url 向伺服器傳送url請求
params 新增查詢引數
**kwargs(headers) 新增請求頭資訊

1.使用get()函式向伺服器傳送HTTP中的get請求

from requests import get
url="http://httpbin.org/get" #1.向伺服器傳送get請求 response=get(url) #2.使用response處理伺服器的響應內容 print(response.text)

2.向原URL後新增查詢資料

from requests import get

url="http://httpbin.org/get"

#1.資料以字典的形式
data={"project":"Python"}

#2.向伺服器傳送get請求
response=get(url,params=data)

#3.使用response處理伺服器的響應內容
print(response.text)

3.新增請求頭資訊

from requests import get

url="http://httpbin.org/get"

#1.資料以字典的形式
data={"project":"Python"}

#2.新增請求頭資訊
headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) "
         "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"}

#3.向伺服器傳送get請求
response=get(url,params=data,headers=headers)

#4.使用response處理伺服器的響應內容
print(response.text)

4.解析json(獲取json格式資料)

from requests import get 

url="http://httpbin.org/get"

response=get(url)
#1.列印響應訊息型別
print(type(response.text))

#2.解析json
print(response.json())
print(type(response.json()))

5.獲取網路上的二進位制資料(圖片、視訊、音訊等)

from requests import get 

url="https://img.alicdn.com/tps/i4/TB1eEBOXsyYBuNkSnfoSuwWgVXa.jpg_1080x1800Q60s50.jpg"

response=get(url)

print(type(response.text))
print(response.content)

#1.以IO流的形式把二進位制圖片資料儲存到本地D盤的某個目錄
with open("D:\\Picture\\6.jpg","wb")as f:
    f.write(response.content)
    f.close()
    print("成功寫入檔案")

(三)post請求的基本用法

def post(url, data=None, json=None, **kwargs)

post()函式

引數 說明
url 向伺服器傳送url請求
data 提交表單的資料
**kwargs(headers) 新增請求頭資訊

1.表單提交使用post請求,用於隱藏資料保證資料安全。

from requests import post

url="http://httpbin.org/post"

#1.提交表單的資料
form_data={"username":"root","password":"123"}

#2.將表單資料賦值給Params引數
reponse=post(url,data=form_data)

#3.列印伺服器響應內容
print(reponse.text)

2.新增響應頭資訊(模擬真實瀏覽器)

from requests import post

url="http://httpbin.org/post"

#1.提交表單的資料
form_data={"username":"root","password":"123"}

headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"}

#2.將表單資料賦值給Params引數
reponse=post(url,data=form_data,headers=headers)

#3.列印伺服器響應內容
print(reponse.text)

(四)response響應基本處理

屬性 說明
response.text 獲取響應文字
response.content 獲取網頁上的二進位制圖片、視訊
response.encoding 獲取網頁編碼
response.encoding=”utf-8” 設定網頁編碼
response.status_code 獲取響應狀態碼
response.headers 獲取響應頭資訊
response.cookies 獲取cookies資訊
response.url 獲取url資訊
response.history 獲取history資訊

1.使用reponse物件處理伺服器響應

from requests import get

url="http://www.jianshu.com"

response=get(url)

#1.列印響應狀態碼
print(type(response.status_code),response.status_code)

#2.列印響應頭資訊
print(type(response.headers),response.headers)

#3.列印cookies資訊
print(type(response.cookies),response.cookies)

#4.列印URL
print(type(response.url),response.url)

#5.列印history
print(type(response.history),response.history)

2.狀態碼的判斷


from requests import get

url="https://www.baidu.com/"

response=get(url)

#1.如果響應狀態碼是200,說明請求成功!
if response.status_code==200:
    print("成功請求響應!")
else:
    print("請求失敗!")

(五)提交檔案和影象操作

在網路上上傳檔案非常普遍,但是對於網路資料採集我們不怎麼使用。如果向為自己網站的寫一個檔案上傳功能,可以使用Python實現。

1.上傳圖片到某個網頁


from requests import post

#1.字典的鍵可以任意取名
files={"upload":open('D:\\Picture\\6.jpg',"rb")}

url="http://httpbin.org/post"

#2.將字典賦值個files引數
response=post(url,files=files)

print(response.content)

print(response.text)

(六)處理cookie

Cookie 是在 HTTP 協議下,伺服器或指令碼可以維護客戶工作站上資訊的一種方式。Cookie 是由 Web 伺服器儲存在使用者瀏覽器(客戶端)上的小文字檔案,它可以包含有關使用者的資訊。無論何時使用者連結到伺服器,Web 站點都可以訪問 Cookie 資訊,目前有些 Cookie 是臨時的,有些則是持續的。臨時的 Cookie 只在瀏覽器上儲存一段規定的時間,一旦超過規定的時間,該 Cookie 就會被系統清除。

持續的 Cookie 則儲存在使用者的 Cookie 檔案中,下一次使用者返回時,仍然可以對它進行呼叫。在 Cookie 檔案中儲存 Cookie,有些使用者擔心 Cookie 中的使用者資訊被一些別有用心的人竊取,而造成一定的損害。其實,網站以外的使用者無法跨過網站來獲得 Cookie 資訊。如果因為這種擔心而遮蔽 Cookie,肯定會因此拒絕訪問許多站點頁面。因為,當今有許多 Web 站點開發人員使用 Cookie 技術,例如 Session 物件的使用就離不開 Cookie 的支援。

1.列印瀏覽器中的cookie資訊

from requests import get

url="https://www.baidu.com/"

headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64)"
         " AppleWebKit/537.36 (KHTML, like Gecko) "
         "Chrome/63.0.3239.132 Safari/537.36"}

response=get(url,headers=headers)

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

2.如果想自定義Cookie值傳送出去,可以使用以下方式:

from requests import get

url="https://www.baidu.com"

headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64)"
         " AppleWebKit/537.36 (KHTML, like Gecko) "
         "Chrome/63.0.3239.132 Safari/537.36"}

#1.攜帶cookie資訊
cookies=dict(username='root',password='123')

#2.將cookies打包傳送到伺服器
response=get(url,headers=headers,cookies=cookies)

#3.response處理cookie資訊
print(response.cookies)

3.自動處理Cookie

有時候我們不需要關心Cookie值是多少,只希望每次訪問網頁的時候,程式自動把Cookie值帶上,就向瀏覽器每次訪問伺服器網頁時自動帶有Cookie值。Requests庫提供一個session物件,在連續訪問網頁,處理登陸非常方便。

方式一:

from requests import post,Session

url="http://www.xxx.com/login"

#1.建立Session物件
session=Session()

#2.首次訪問登陸介面,作為遊客伺服器會先分配一個cookie
response=session.get(url,allow_redirects=True)

#3.使用字典儲存登陸資訊
datas={"username":"root","password":"123"}

#4.向登陸連結傳送post請求,驗證成功,遊客許可權轉變為會員許可權
response01=session.post(url,data=datas,allow_redirects=True)

print(response01.text)


----------
方式二:
from requests import get,post,Session

session=Session()

url="http://www.xxx.com/login"

datas={"username":"root","password":"123"}

response01=session.post(url,data=datas)

print("cookie設定為:")

print(session.cookies.get_dict())

print("------------------------")

print("登陸成功後,可以訪問會員許可權的任意網頁!")

#1.登陸過後,訪問網站的其他頁面
response02=session.get("http://www.xxx.com/page01")

4.例項演示

import requests

session= requests.session()
url = 'https://www.douban.com/'
#1.輸入賬號和密碼
postdata = {
    'username':'xxxxxx',
    'password':'xxxxxx'
}
headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36'}
response= session.post(url, data=postdata,headers=headers)
#2.將從網上爬取的資料儲存到本地,再開啟本地html檔案驗證爬取的網頁
#是否是目標網頁
with open('D:\\index.html', 'wb') as f:
    f.write(response.content)

url01 = 'https://movie.douban.com/'
response = session.get(url01, headers=headers)
with open('D:\\movie.html', 'wb') as f:
    f.write(response.content)

(七)重定向與歷史訊息

處理重定向只需要設定一下allow_redirects欄位即可,allow_redirects=True,則允許重定向,allow_redirects=False,則禁止重定向。通過response.history欄位檢視歷史資訊,即訪問成功之前的所有請求跳轉資訊。

1.將所HTTP請求全部重定向為HTTPS

from requests import get,post,Session

response=get("http://github.com")

print(response.url)

print(response.status_code)

print(response.history)

(八)請求超時設定

超時選項是通過get()和post()函式中timeout來進行設定。如果傳送的HTTP請求超時,則丟擲一個 Timeout 異常。

timeout設定的時間是以秒為單位

resquests.get("http://www.baidu.com/",timeout=1)

(九)代理設定

import requests

proxies={"http":"http://0.10.1.10:3128",

          "https":"https//10.10.1.10.1080"}

requests.get("http://example.org",proxies=proxies)

(十)錯誤與異常

  • 遇到網路問題(如:DNS 查詢失敗、拒絕連線等)時,Requests 會丟擲一個 ConnectionError 異常。
  • 如果 HTTP 請求返回了不成功的狀態碼, Response.raise_for_status() 會丟擲一個 HTTPError 異常。

    1. 若請求超時,則丟擲一個 Timeout 異常。
    2. 若請求超過了設定的最大重定向次數,則會丟擲一個 TooManyRedirects 異常。
    3. 所有Requests顯式丟擲的異常都繼承自 requests.exceptions.RequestException 。

    (十一)證書驗證

安全性較高的網站和公司網站都使用了證書驗證,比如www.12306.cn。

1.直接訪問www.12306.cn,報SSLError異常。


import requests

response=requests.get("https://www.12306.cn")

print(response.status_code)

異常資訊:

SSLError: HTTPSConnectionPool(host='www.12306.cn', port=443):
 Max retries exceeded with url: / (Caused by SSLError(SSLError
 , 'certificate verify failed')],)",),))

2.證書認證成功的操作方法

import requests

#1.匯入urllib3
from requests.packages import urllib3

#2.呼叫以下方法消除警告
urllib3.disable_warnings()

#3.將verify屬性設定為Fales
response=requests.get("https://www.12306.cn",verify=False)

print(response.status_code)

(十二)HTTP基本接入認證設定

在發明cookie前,處理網站登陸最常用的方法就是HTTP基本接入認證。意思就是需要輸入賬號和密碼才能登陸某個網址訪問其頁面。


import requests

from requests.auth import HTTPBasicAuth

url="http://pythonscraping.com/pages/auth/login.php"

#1.設定登陸賬號和密碼
auth=HTTPBasicAuth("Kaina","123")

#2.將HTTPBasicAuth物件作為auth引數傳遞到請求中
response=requests.post(url,auth=auth)

print(response.status_code)

#3.列印登陸跳轉成功頁面的HTML
print(response.text)

(十三)獲取Boss直聘網Python爬蟲職位資訊

如圖所示:
這裡寫圖片描述
1.程式碼演示

import requests
import pandas as pd
from lxml import etree
from urllib.error import HTTPError,URLError
def getHtml(url):
    #攜帶請求頭資訊,否則無法獲取資料
    headers={"User-Agent":"Mozilla/5.0"}
    try:
        response=requests.get(url,headers=headers)
    except(HTTPError, URLError) as e:
        return None
    return response.text
def parseHtml(html):
    tree=etree.HTML(html)
    positions=tree.xpath('//div[@class="job-title"]/text()')
    companies=tree.xpath('//div[@class="company-text"]/h3[@class="name"]/a/text()')
    salarys=tree.xpath('//div/div/h3/a/span/text()')
    releasetime=tree.xpath('//div[@class="info-publis"]/p/text()')
    return positions,companies,salarys,releasetime
def go():
    position=[]
    companies=[]
    releasetime=[]
    salarys=[]
    for i in range(8):
        url = "https://www.zhipin.com/c101280600/h_101280600/?query=python爬蟲工程師&page="+str(1+i)+"&ka=page-"+str(i+1)
        html = getHtml(url)
        if html !=None:
            p, c, s, r = parseHtml(html)
            position += p
            companies += c
            salarys += s
            releasetime += r
    dic = {"職位": position, "公司": companies,"薪水":salarys, "發表時間": releasetime}
    df = pd.DataFrame(dic)
    df.to_excel("Test.xlsx", index=False)

if __name__ == '__main__':
     go()
     print("資料寫入完畢!")

結果:
這裡寫圖片描述