1. 程式人生 > >Python爬蟲(八)_Requests的使用

Python爬蟲(八)_Requests的使用

get請求 ron gpo sta session 跳過 aps 訪問 txt

Requests:讓HTTP服務人類

雖然Python的標準庫中urllib2模塊中已經包含了平常我們使用的大多數功能,但是它的API使用起來讓人感覺不太好,而Requests自稱"HTTP for Humans",說明使用更簡單方便。

Requests唯一的一個非轉基因的Python HTTP庫,人類可以安全享用

Requests繼承了urllib2的所有特性。Requests支持HTTP連接保持和連接池,支持使用cookie保持會話,支持文件上傳,支持自動確定響應內容的編碼,支持國際化的URL和POST數據自動編碼。

requests的底層實現其實就是urllib3

Requests的文檔非常完備,中文文檔也相當不錯。Requests能完全滿足當前網絡的需求,支持Python2.6-3.5,而且能在PyPy下完美運行。

開源首地址:https://github.com/kennethreitz/requests

中文文檔API: http://docs.python-requests.org/zh_CN/latest/index.html

安裝方式

利用pip安裝或者利用easy_install都可以完成安裝:

$pip install requests

$easy_install requests

基本GET請求(headers參數和parmas參數)

  1. 最基本的GET請求可以直接用get方法
response = requests.get("http://www.baidu.com/")

#也可以這麽寫
#response = requests.request("get", "http://www.baidu.com/")
  1. 添加headers和查詢參數

如果想添加headers,可以傳入headers參數來參加請求頭中的headers信息,如果要將參數放在url中傳遞,可以利用params參數。

import requests

kw = {‘wd‘:‘長城‘}

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

#params接收一個字典或者字符串的查詢參數,字典類型自動轉換為url編碼,不需要urlencode()
response = requests.get("http://www.baidu.com/s?", params=kw, headers = headers)

#查看響應內容,response.text返回的是Unicode格式的數據
print(response.text)

#查看響應內容,response.content返回的字節流數據
print(response.content)

#查看完整url地址
print(response.url)

#查看響應頭部字符編碼
print(response.encoding)

#查看響應碼
print(response.status_code)

運行結果

......

......

‘http://www.baidu.com/s?wd=%E9%95%BF%E5%9F%8E‘

‘utf-8‘

200
  • 使用response.text時,Requests會基於HTTP響應的文本編碼自動解碼響應內容,大多數Unicode字符集都能被無縫地解碼。
  • 使用response.content時,返回的是服務器響應數據的原始二進制字節流,可以用來保存圖片等二進制文件。

基本POST請求(data參數)

  1. 最基本的GET請求可以直接用post方法
response = requests.post("http://www.baidu.com/", data=data)
  1. 傳入data數據
    對於POST請求來說,我們一般需要為它增加一些參數。那麽醉基本的穿參方法可以利用data這個參數。
import requests

formdata = {
    "type":"AUTO",
    "i":"i love python",
    "doctype":"json",
    "xmlVersion":"1.8",
    "keyfrom":"fanyi.web",
    "ue":"UTF-8",
    "action":"FY_BY_ENTER",
    "typoResult":"true"
}

url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null"

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

response = requests.post(url, data=formdata, headers=headers)

print(response.text)

#如果是json文件可以直接顯示
print(response.json())

運行結果

{"type":"EN2ZH_CN","errorCode":0,"elapsedTime":2,"translateResult":[[{"src":"i love python","tgt":"我喜歡python"}]],"smartResult":{"type":1,"entries":["","肆文","高德納"]}}

{u‘errorCode‘: 0, u‘elapsedTime‘: 0, u‘translateResult‘: [[{u‘src‘: u‘i love python‘, u‘tgt‘: u‘\u6211\u559c\u6b22python‘}]], u‘smartResult‘: {u‘type‘: 1, u‘entries‘: [u‘‘, u‘\u8086\u6587‘, u‘\u9ad8\u5fb7\u7eb3‘]}, u‘type‘: u‘EN2ZH_CN‘}

代理(proxies參數)

如果需要使用代理,你可以通過為任意請求方法提供proxies參數來配置單個請求:

import requests
#根據協議內容,選擇不同的代理
proxies = {
    "http":"http://12.34.56.79:9527",
    "https":"http://12.34.56.79:9527"
}

response = requests.get("http://www.baidu.com", proxies = proxies)
print(response.text)

也可以通過本地環境變量HTTP_PROXYHTTPS_PROXY來配置代理:

export HTTP_PROXY="http://12.34.56.79:9527"
export HTTPS_PROXY="https://12.34.56.79:9527"

私密代理驗證(特定格式)和Web客戶端驗證(auth參數)

urllib2這裏的做法比較復雜,requests只需要一步:

私密代理

import requests

#如果帶來需要使用HTTP Basic Auth,可以使用下面這種格式:
proxy = {"http":"mr_mao_hacker:[email protected]:16816"}

response = requests.get("http://www.baidu.com", proxies=proxy)

print(response.text)

web客戶端驗證

如果是Web客戶端驗證,需要添加auth=(賬戶名,密碼)

import requests

auth={"test":"123456"}

response = requests.get("http://192.168.199.107", auth=auth)

print(response.text)

urllib2淚奔...

Cookies和Sission

Cookies
如果一個相應中包含了cookie,那麽我們可以利用cookies參數拿到:

import requests

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

#7.返回cookieJar對象:
cookiejar = response.cookies

#8.將CookieJar轉為字典:
cookiedict = requests.utils.dict_from_cookiejar(cookiejar)

print(cookiejar)

print(cookiedict)

運行結果:

<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>

{‘BDORZ‘: ‘27315‘}

**Session
在requests裏,session對象是一個非常常用的對象,這個對象代表依次用戶會話:從客戶端瀏覽器連接服務器開始,到客戶端瀏覽器與服務器斷開。

會話能讓我們在跨請求時候保持某些參數,比如在同一個Session實例發出的所有請求之間保持cookie

實現人人網登陸

import requests

#1.創建session對象,可以保存Cookie值
ssion = requests.session()

#2.處理headers
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}

#3.需要登陸的用戶名和密碼
data={"email":"[email protected]", "passwd":"alarmchime"}

#4.發送附帶用戶名和密碼的請求,並獲取登陸後的Cookie的值,保存在session裏
ssion.post("http://www.renren.com/PLogin.do", data=data)

#5.ssion包含用戶登陸後的cookie值,可以直接訪問那些登陸後的頁面
response = ssion.get("http://www.renren.com/410043129/profile")

#6.打印響應內容
print(response.text)

技術分享圖片

處理HTTPS請求SSL證書驗證

Requests也可以為HTTPS請求驗證SSL證書:

  • 要想檢查某個主機的SSL證書,你可以使用verify(也可以不寫)
import requests
response = requests.get("https://www.baidu.com", verify=true)

#也可以省略不寫
#response = requests.get("https://www.baidu.com/")
print r.txt

運行結果:

<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge>百度一下,你就知道 
  • 如果SSL證書驗證不通過,或者不信任服務器的安全證書,則會報出SSLError,據說12306證書是自己做的:

技術分享圖片

來測試一下:

import requests

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

print(response.text)

果然:

SSLError: ("bad handshake: Error([(‘SSL routines‘, ‘ssl3_get_server_certificate‘, ‘certificate verify failed‘)],)",)

如果我們想跳過12306的證書驗證,把verify設置為False就可以正常請求了。

r = requests.get("https://www.12306.cn/mormhweb/", verify = False)

Python爬蟲(八)_Requests的使用