python爬蟲之requests庫的使用詳解

python爬蟲—requests庫的用法

requests是python實現的簡單易用的HTTP庫,使用起來比urllib簡潔很多,requests 允許你發送 HTTP/1.1 請求。指定 URL並添加查詢url字符串即可開始爬取網頁信息等操作

因為是第三方庫,所以使用前需要cmd安裝

pip install requests

安裝完成後import一下,正常則說明可以開始使用瞭

基本用法:

requests.get()用於請求目標網站,類型是一個HTTPresponse類型

import requests
response = requests.get('http://www.baidu.com')
print(response.status_code)  # 打印狀態碼
print(response.url)          # 打印請求url
print(response.headers)      # 打印頭信息
print(response.cookies)      # 打印cookie信息
print(response.text)  #以文本形式打印網頁源碼
print(response.content) #以字節流形式打印

以打印狀態碼為例,運行結果:

在這裡插入圖片描述

狀態碼:200,證明請求目標網站正常

若狀態碼為403一般是目標存有防火墻,觸發瞭反爬策略被限制瞭IP

各種請求方式:

import requests
requests.get('http://www.baidu.com')
requests.post('http://www.baidu.com')
requests.put('http://www.baidu.com')
requests.delete('http://www.baidu.com')
requests.head('http://www.baidu.com')
requests.options('http://www.baidu.com')

基本的get請求

import requests
response = requests.get('http://www.baidu.com')
print(response.text)

在這裡插入圖片描述

帶參數的GET請求:

第一種直接將參數放在url內

import requests
response = requests.get("https://www.crrcgo.cc/admin/crr_supplier.html?params=1")
print(response.text)

在這裡插入圖片描述

另一種先將參數填寫在data中,發起請求時將params參數指定為data

import requests
data = {
    'params': '1',
}
response = requests.get('https://www.crrcgo.cc/admin/crr_supplier.html?', params=data)
print(response.text)

在這裡插入圖片描述

基本POST請求:

import requests
response = requests.post('http://baidu.com')

在這裡插入圖片描述

解析json

import requests
response = requests.get('http://httpbin.org/get')
print(response.text)
print(response.json())  #response.json()方法同json.loads(response.text)
print(type(response.json()))

在這裡插入圖片描述

簡單保存一個二進制文件

import requests
response = requests.get('http://img.ivsky.com/img/tupian/pre/201708/30/kekeersitao-002.jpg')
b = response.content
with open('F://fengjing.jpg','wb') as f:
    f.write(b)

為你的請求添加頭信息

import requests
heads = {}
heads['User-Agent'] = 'Mozilla/5.0 ' \
                          '(Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 ' \
                          '(KHTML, like Gecko) Version/5.1 Safari/534.50'
 response = requests.get('http://www.baidu.com',headers=headers)

此方法可以有效地避開防火墻的檢測,隱藏自己身份

使用代理

同添加headers方法一樣,代理參數也是一個dict這裡使用requests庫爬取瞭IP代理網站的IP與端口和類型。因為是免費的,使用的代理地址很快就失效瞭。

復制代碼

import requests
import re
def get_html(url):
    proxy = {
        'http': '120.25.253.234:812',
        'https' '163.125.222.244:8123'
    }
    heads = {}
    heads['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0'
    req = requests.get(url, headers=heads,proxies=proxy)
    html = req.text
    return html
def get_ipport(html):
    regex = r'<td data-title="IP">(.+)</td>'
    iplist = re.findall(regex, html)
    regex2 = '<td data-title="PORT">(.+)</td>'
    portlist = re.findall(regex2, html)
    regex3 = r'<td data-title="類型">(.+)</td>'
    typelist = re.findall(regex3, html)
    sumray = []
    for i in iplist:
        for p in portlist:
            for t in typelist:
                pass
            pass
        a = t+','+i + ':' + p
        sumray.append(a)
    print('高匿代理')
    print(sumray)
if __name__ == '__main__':
    url = 'http://www.baidu.com'
    get_ipport(get_html(url))

獲取cookie

import requests
response = requests.get('http://www.baidu.com')
print(response.cookies)
print(type(response.cookies))
for k,v in response.cookies.items():
    print(k+':'+v)

在這裡插入圖片描述

會話維持

import requests
session = requests.Session()
session.get('https://www.crrcgo.cc/admin/crr_supplier.html')
response = session.get('https://www.crrcgo.cc/admin/')
print(response.text)

證書驗證設置

import requests
from requests.packages import urllib3
urllib3.disable_warnings()  #從urllib3中消除警告
response = requests.get('https://www.12306.cn',verify=False)  #證書驗證設為FALSE
print(response.status_code)

超時異常捕獲

import requests
from requests.exceptions import ReadTimeout
try:
    res = requests.get('http://httpbin.org', timeout=0.1)
    print(res.status_code)
except ReadTimeout:
    print(timeout)

異常處理

使用try…except來捕獲異常

import requests
from requests.exceptions import ReadTimeout,HTTPError,RequestException
try:
    response = requests.get('http://www.baidu.com',timeout=0.5)
    print(response.status_code)
except ReadTimeout:
    print('timeout')
except HTTPError:
    print('httperror')
except RequestException:
    print('reqerror')

總結

本篇文章就到這裡瞭,希望能夠給你帶來幫助,也希望您能夠多多關註WalkonNet的更多內容!

推薦閱讀: