Python入妖4-----Request庫的基本使用


什么是Requests

Requests是用python語言基於urllib編寫的,采用的是Apache2 Licensed開源協議的HTTP庫
如果你看過上篇文章關於urllib庫的使用,你會發現,其實urllib還是非常不方便的,而Requests它會比urllib更加方便,可以節約我們大量的工作。(用了requests之后,你基本都不願意用urllib了)一句話,requests是python實現的最簡單易用的HTTP庫,建議爬蟲使用requests庫。

默認安裝好python之后,是沒有安裝requests模塊的,需要單獨通過pip安裝

requests功能詳解

總體功能的一個演示

import requests

response  = requests.get("https://www.baidu.com")
print(type(response))
print(response.status_code)
print(type(response.text))
print(response.text)
print(response.cookies)
print(response.content)
print(response.content.decode("utf-8"))

我們可以看出response使用起來確實非常方便,這里有個問題需要注意一下:
很多情況下的網站如果直接response.text會出現亂碼的問題,所以這個使用response.content
這樣返回的數據格式其實是二進制格式,然后通過decode()轉換為utf-8,這樣就解決了通過response.text直接返回顯示亂碼的問題.

請求發出后,Requests 會基於 HTTP 頭部對響應的編碼作出有根據的推測。當你訪問 response.text 之時,Requests 會使用其推測的文本編碼。你可以找出 Requests 使用了什么編碼,並且能夠使用 response.encoding 屬性來改變它.如:

response =requests.get("http://www.baidu.com")
response.encoding="utf-8"
print(response.text)

各種請求方式

requests里提供個各種請求方式

import requests
requests.post("http://httpbin.org/post")
requests.put("http://httpbin.org/put")
requests.delete("http://httpbin.org/delete")
requests.head("http://httpbin.org/get")
requests.options("http://httpbin.org/get")

請求

基本GET請求

import requests

response = requests.get('http://httpbin.org/get')
print(response.text)

帶參數的GET請求,例子1

import requests

response = requests.get("http://httpbin.org/get?name=zhaofan&age=23")
print(response.text)

如果我們想要在URL查詢字符串傳遞數據,通常我們會通過httpbin.org/get?key=val方式傳遞。Requests模塊允許使用params關鍵字傳遞參數,以一個字典來傳遞這些參數,例子如下:

import requests
data = {
    "name":"zhaofan",
    "age":22
}
response = requests.get("http://httpbin.org/get",params=data)
print(response.url)
print(response.text

上述兩種的結果是相同的,通過params參數傳遞一個字典內容,從而直接構造url
注意:第二種方式通過字典的方式的時候,如果字典中的參數為None則不會添加到url上

解析json

import requests
import json

response = requests.get("http://httpbin.org/get")
print(type(response.text))

print(response.json()) print(json.loads(response.text))
print(type(response.json()))

從結果可以看出requests里面集成的json其實就是執行了json.loads()方法,兩者的結果是一樣的

獲取二進制數據

在上面提到了response.content,這樣獲取的數據是二進制數據,同樣的這個方法也可以用於下載圖片以及
視頻資源

添加headers

和前面我們將urllib模塊的時候一樣,我們同樣可以定制headers的信息,如當我們直接通過requests請求知乎網站的時候,默認是無法訪問的

import requests
response =requests.get("https://www.zhihu.com")
print(response.text)

這樣會得到如下的錯誤

因為訪問知乎需要頭部信息,這個時候我們在谷歌瀏覽器里輸入chrome://version,就可以看到用戶代理,將用戶代理添加到頭部信息

import requests
headers = {

    "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
}
response =requests.get("https://www.zhihu.com",headers=headers)

print(response.text)

 這樣就可以正常的訪問知乎了。

基本POST請求

通過在發送post請求時添加一個data參數,這個data參數可以通過字典構造成,這樣
對於發送post請求就非常方便

import requests

data = {
    "name":"zhaofan",
    "age":23
}
response = requests.post("http://httpbin.org/post",data=data)
print(response.text)

 同樣的在發送post請求的時候也可以和發送get請求一樣通過headers參數傳遞一個字典類型的數據

 響應

 我們可以通過response獲得很多屬性,例子如下

import requests

response = requests.get("http://www.baidu.com")
print(type(response.status_code),response.status_code)
print(type(response.headers),response.headers)
print(type(response.cookies),response.cookies)
print(type(response.url),response.url)
print(type(response.history),response.history)

結果如下:

狀態碼判斷

Requests還附帶了一個內置的狀態碼查詢對象
主要有如下內容:

100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),

Redirection.

300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect',
'resume_incomplete', 'resume',), # These 2 to be removed in 3.0

Client Error.

400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),

Server Error.
500: ('internal_server_error', 'server_error', '/o\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication'),

通過下面例子測試:(不過通常還是通過狀態碼判斷更方便)

import requests

response= requests.get("http://www.baidu.com")
if response.status_code == requests.codes.ok:
    print("訪問成功")

項目實例:

使用流程

  • 指定url
  • 基於requests模塊發起請求
  • 獲取響應對象中的數據值
  • 持久化存儲

1、需求:爬取搜狗指定詞條搜索后的頁面數據 

 

import requests
import os
#指定搜索關鍵字
word = input('enter a word you want to search:')
#自定義請求頭信息
headers={
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
#指定url
url = 'https://www.sogou.com/web'
#封裝get請求參數
param = {
    'query':word,
    'ie':'utf-8'
}
#發起請求
response = requests.get(url=url,params=param)

#獲取響應數據
page_text = response.text

with open('./sougou.html','w',encoding='utf-8') as fp:
    fp.write(page_text)
View Code

2、需求:登錄豆瓣電影,爬取登錄成功后的頁面數據 

import requests
import os
url = 'https://accounts.douban.com/login'
#封裝請求參數
data = {
    "source": "movie",
    "redir": "https://movie.douban.com/",
    "form_email": "15027900535",
    "form_password": "bobo@15027900535",
    "login": "登錄",
}
#自定義請求頭信息
headers={
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
response = requests.post(url=url,data=data)
page_text = response.text

with open('./douban111.html','w',encoding='utf-8') as fp:
    fp.write(page_text)
View Code

 

3、需求:爬取豆瓣電影分類排行榜 https://movie.douban.com/中的電影詳情數據 

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import requests
import urllib.request
if __name__ == "__main__":

    #指定ajax-get請求的url(通過抓包進行獲取)
    url = 'https://movie.douban.com/j/chart/top_list?'

    #定制請求頭信息,相關的頭信息必須封裝在字典結構中
    headers = {
        #定制請求頭中的User-Agent參數,當然也可以定制請求頭中其他的參數
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
    }

    #定制get請求攜帶的參數(從抓包工具中獲取)
    param = {
        'type':'5',
        'interval_id':'100:90',
        'action':'',
        'start':'0',
        'limit':'20'
    }
    #發起get請求,獲取響應對象
    response = requests.get(url=url,headers=headers,params=param)

    #獲取響應內容:響應內容為json串
    print(response.text)
View Code

 

 

 

4、需求:爬取肯德基餐廳查詢http://www.kfc.com.cn/kfccda/index.aspx中指定地點的餐廳數據 

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import requests
import urllib.request
if __name__ == "__main__":

    #指定ajax-post請求的url(通過抓包進行獲取)
    url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword'

    #定制請求頭信息,相關的頭信息必須封裝在字典結構中
    headers = {
        #定制請求頭中的User-Agent參數,當然也可以定制請求頭中其他的參數
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',
    }

    #定制post請求攜帶的參數(從抓包工具中獲取)
    data = {
        'cname':'',
        'pid':'',
        'keyword':'北京',
        'pageIndex': '1',
        'pageSize': '10'
    }
    #發起post請求,獲取響應對象
    response = requests.get(url=url,headers=headers,data=data)

    #獲取響應內容:響應內容為json串
    print(response.text)
View Code

 

 

 

5、需求:爬取搜狗知乎指定詞條指定頁碼下的頁面數據 

import requests
import os
#指定搜索關鍵字
word = input('enter a word you want to search:')
#指定起始頁碼
start_page = int(input('enter start page num:'))
end_page = int(input('enter end page num:'))
#自定義請求頭信息
headers={
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
#指定url
url = 'https://zhihu.sogou.com/zhihu'
#創建文件夾
if not os.path.exists('./sougou'):
    os.mkdir('./sougou')
for page in range(start_page,end_page+1):
    #封裝get請求參數
    params = {
        'query':word,
        'ie':'utf-8',
        'page':str(page)
    }
    #發起post請求,獲取響應對象
    response = requests.get(url=url,params=params)
    #獲取頁面數據
    page_text = response.text
    fileName = word+'_'+str(page)+'.html'
    filePath = './sougou/'+fileName
    with open(filePath,'w',encoding='utf-8') as fp:
        fp.write(page_text)
        print('爬取'+str(page)+'頁結束')
View Code

 

requests高級用法

文件上傳

實現方法和其他參數類似,也是構造一個字典然后通過files參數傳遞

import requests
files= {"files":open("git.jpeg","rb")}
response = requests.post("http://httpbin.org/post",files=files)
print(response.text)

 結果如下:

獲取cookie

import requests

response = requests.get("http://www.baidu.com")
print(response.cookies)

for key,value in response.cookies.items():
    print(key+"="+value)

 會話維持

 cookie的一個作用就是可以用於模擬登陸,做會話維持

import requests
s = requests.Session()
s.get("http://httpbin.org/cookies/set/nufffmber/123456")
response = s.get("http://httpbin.org/cookies")
print(response.text)

 這是正確的寫法,而下面的寫法則是錯誤的

import requests

requests.get("http://httpbin.org/cookies/set/number/123456")
response = requests.get("http://httpbin.org/cookies")
print(response.text)

因為這種方式是兩次requests請求之間是獨立的,而第一次則是通過創建一個session對象,兩次請求都通過這個對象訪問

證書驗證

現在的很多網站都是https的方式訪問,所以這個時候就涉及到證書的問題

import requests

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

為了避免這種情況的發生可以通過 verify=False
但是這樣是可以訪問到頁面,但是會提示:

InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning)

解決方法為:

import requests
from requests.packages import urllib3

urllib3.disable_warnings()
response = requests.get("https://www.12306.cn",verify=False)
print(response.status_code)

這樣就不會提示警告信息,當然也可以通過cert參數放入證書路徑 

代理設置

import requests

proxies= {
    "http":"http://127.0.0.1:9999",
    "https":"http://127.0.0.1:8888"
}
response  = requests.get("https://www.baidu.com",proxies=proxies)
print(response.text)

 如果代理需要設置賬戶名和密碼,只需要將字典更改為如下:
proxies = {
"http":"http://user:password@127.0.0.1:9999"
}
如果你的代理是通過sokces這種方式則需要pip install "requests[socks]"
proxies= {
"http":"socks5://127.0.0.1:9999",
"https":"sockes5://127.0.0.1:8888"
}

超時設置

通過timeout參數可以設置超時的時間

認證設置

如果碰到需要認證的網站可以通過requests.auth模塊實現

import requests

from requests.auth import HTTPBasicAuth

response = requests.get("http://120.27.34.24:9001/",auth=HTTPBasicAuth("user","123"))
print(response.status_code)

當然這里還有一種方式

import requests

response = requests.get("http://120.27.34.24:9001/",auth=("user","123"))
print(response.status_code)

異常處理

關於reqeusts的異常在這里可以看到詳細內容:
http://www.python-requests.org/en/master/api/#exceptions
所有的異常都是在requests.excepitons中

從源碼我們可以看出RequestException繼承IOError,
HTTPError,ConnectionError,Timeout繼承RequestionException
ProxyError,SSLError繼承ConnectionError
ReadTimeout繼承Timeout異常
這里列舉了一些常用的異常繼承關系,詳細的可以看:
http://cn.python-requests.org/zh_CN/latest/_modules/requests/exceptions.html#RequestException

通過下面的例子進行簡單的演示

import requests
from requests.exceptions import ReadTimeout,ConnectionError,RequestException

try:
    response = requests.get("http://httpbin.org/get",timeout=0.1)
    print(response.status_code)
except ReadTimeout:
    print("timeout")
except ConnectionError:
    print("connection Error")
except RequestException:
    print("error")

 其實最后測試可以發現,首先被捕捉的異常是timeout,當把網絡斷掉的haul就會捕捉到ConnectionError,如果前面異常都沒有捕捉到,最后也可以通過RequestExctption捕捉到

 

項目實例:

cookie和代理實例

一、基於requests模塊的cookie操作

引言:有些時候,我們在使用爬蟲程序去爬取一些用戶相關信息的數據(爬取張三“人人網”個人主頁數據)時,如果使用之前requests模塊常規操作時,往往達不到我們想要的目的,例如:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
if __name__ == "__main__":

    #張三人人網個人信息頁面的url
    url = 'http://www.renren.com/289676607/profile'

   #偽裝UA
    headers={
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
    #發送請求,獲取響應對象
    response = requests.get(url=url,headers=headers)
    #將響應內容寫入文件
    with open('./renren.html','w',encoding='utf-8') as fp:
        fp.write(response.text)

 

結果發現,寫入到文件中的數據,不是張三個人頁面的數據,而是人人網登陸的首頁面,why?首先我們來回顧下cookie的相關概念及作用:

cookie概念:當用戶通過瀏覽器首次訪問一個域名時,訪問的 web服務器會給客戶端發送數據,以保持web服務器與客戶端之間的狀態保持,這些數據就是cookie。

cookie作用:我們在瀏覽器中,經常涉及到數據的交換,比如你登錄郵箱,登錄一個頁面。我們經常會在此時設置30天內記住我,或者自動登錄選項。那么它們是怎么記錄信息的呢,答案就是今天的主角cookie了,Cookie是由HTTP服務器設置的,保存在瀏覽器中,但HTTP協議是一種無狀態協議,在數據交換完畢后,服務器端和客戶端的鏈接就會關閉,每次交換數據都需要建立新的鏈接。就像我們去超市買東西,沒有積分卡的情況下,我們買完東西之后,超市沒有我們的任何消費信息,但我們辦了積分卡之后,超市就有了我們的消費信息。cookie就像是積分卡,可以保存積分,商品就是我們的信息,超市的系統就像服務器后台,http協議就是交易的過程。

經過cookie的相關介紹,其實你已經知道了為什么上述案例中爬取到的不是張三個人信息頁,而是登錄頁面。那應該如何抓取到張三的個人信息頁呢?

思路

  1、我們需要使用爬蟲程序對人人網的登錄時的請求進行一次抓取,獲取請求中的cookie數據。

  2、在使用個人信息頁的url進行請求時,該請求需要攜帶 1 中的cookie,只有攜帶了cookie后,服務器才可識別這次請求的用戶信息,方可響應回指定的用戶信息頁數據。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
if __name__ == "__main__":

    #登錄請求的url(通過抓包工具獲取)
    post_url = 'http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=201873958471'
    #創建一個session對象,該對象會自動將請求中的cookie進行存儲和攜帶
    session = requests.session()
   #偽裝UA
    headers={
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
    }
    formdata = {
        'email': '17701256561',
        'icode': '',
        'origURL': 'http://www.renren.com/home',
        'domain': 'renren.com',
        'key_id': '1',
        'captcha_type': 'web_login',
        'password': '7b456e6c3eb6615b2e122a2942ef3845da1f91e3de075179079a3b84952508e4',
        'rkey': '44fd96c219c593f3c9612360c80310a3',
        'f': 'https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3Dm7m_NSUp5Ri_ZrK5eNIpn_dMs48UAcvT-N_kmysWgYW%26wd%3D%26eqid%3Dba95daf5000065ce000000035b120219',
    }
    #使用session發送請求,目的是為了將session保存該次請求中的cookie
    session.post(url=post_url,data=formdata,headers=headers)

    get_url = 'http://www.renren.com/960481378/profile'
    #再次使用session進行請求的發送,該次請求中已經攜帶了cookie
    response = session.get(url=get_url,headers=headers)
    #設置響應內容的編碼格式
    response.encoding = 'utf-8'
    #將響應內容寫入文件
    with open('./renren.html','w') as fp:
        fp.write(response.text)

 

二、基於requests模塊的代理操作

  • 什么是代理
    • 代理就是第三方代替本體處理相關事務。例如:生活中的代理:代購,中介,微商......

  • 爬蟲中為什么需要使用代理

    • 一些網站會有相應的反爬蟲措施,例如很多網站會檢測某一段時間某個IP的訪問次數,如果訪問頻率太快以至於看起來不像正常訪客,它可能就會會禁止這個IP的訪問。所以我們需要設置一些代理IP,每隔一段時間換一個代理IP,就算IP被禁止,依然可以換個IP繼續爬取。

  • 代理的分類:

    • 正向代理:代理客戶端獲取數據。正向代理是為了保護客戶端防止被追究責任。

    • 反向代理:代理服務器提供數據。反向代理是為了保護服務器或負責負載均衡。

  • 免費代理ip提供網站

    • http://www.goubanjia.com/

    • 西祠代理

    • 快代理

代碼:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import random
if __name__ == "__main__":
    #不同瀏覽器的UA
    header_list = [
        # 遨游
        {"user-agent": "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)"},
        # 火狐
        {"user-agent": "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"},
        # 谷歌
        {
            "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"}
    ]
    #不同的代理IP
    proxy_list = [
        {"http": "112.115.57.20:3128"},
        {'http': '121.41.171.223:3128'}
    ]
    #隨機獲取UA和代理IP
    header = random.choice(header_list)
    proxy = random.choice(proxy_list)

    url = 'http://www.baidu.com/s?ie=UTF-8&wd=ip'
    #參數3:設置代理
    response = requests.get(url=url,headers=header,proxies=proxy)
    response.encoding = 'utf-8'
    
    with open('daili.html', 'wb') as fp:
        fp.write(response.content)
    #切換成原來的IP
    requests.get(url, proxies={"http": ""})

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM