Python爬蟲之requests庫基本介紹
一、說明
requests是一個很實用的Python HTTP客戶端庫,爬蟲和測試服務器響應數(shù)據(jù)時經(jīng)常會用到,requests是Python語言的第三方的庫,專門用于發(fā)送HTTP請求,使用起來比urllib簡潔很多。
Requests 有這些功能:
1、Keep-Alive & 連接池
2、國際化域名和 URL
3、帶持久 Cookie 的會話
4、瀏覽器式的 SSL 認證
5、自動內(nèi)容解碼
6、基本/摘要式的身份認證
7、優(yōu)雅的 key/value Cookie
8、自動解壓
9、Unicode 響應體
10、HTTP(S) 代理支持
11、文件分塊上傳
12、流下載
13、連接超時
14、分塊請求
15、支持 .netrc
Requests 支持 Python 2.6—2.7以及3.3—3.7,而且能在 PyPy 下完美運行。
用pip進行第三方庫的安裝
pip install requests
安裝完成后import一下,正常則說明可以開始使用了。
二、基本用法:
1、requests.get()
用于請求目標網(wǎng)站,類型是一個HTTPresponse類型
import requests
response = requests.get('http://www.baidu.com')
print(response.status_code) # 打印狀態(tài)碼
print(response.url) # 打印請求url
print(response.headers) # 打印頭信息
print(response.cookies) # 打印cookie信息
print(response.text) #以文本形式打印網(wǎng)頁源碼
print(response.content) #以字節(jié)流形式打印
print(response.content.decode("utf-8")) #解決了通過response.text直接返回顯示亂碼的問題
response.encoding="utf-8" #避免亂碼的問題發(fā)生
2、各種請求方式
import requests
requests.get('http://httpbin.org/get')
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')
3、基本的get請求
import requests
response = requests.get('http://httpbin.org/get')
print(response.text)
4、帶參數(shù)的get請求
第一種直接將參數(shù)放在url內(nèi)
import requests response = requests.get(http://httpbin.org/get?name=gemey&age=22) print(response.text)
另一種先將參數(shù)填寫在dict中,發(fā)起請求時params參數(shù)指定為dict
import requests
data = {
'name': 'tom',
'age': 20
}
response = requests.get('http://httpbin.org/get', params=data)
print(response.text)
5、解析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()))
如果 JSON 解碼失敗, 將會拋出 ValueError: No JSON object could be decoded 異常。而成功調(diào)用 response.json() 并不意味著響應的成功。有的服務器會在失敗的響應中包含一個 JSON 對象(比如 HTTP 500 的錯誤細節(jié))。這種 JSON 會被解碼返回。要檢查請求是否成功,請使用 r.raise_for_status() 或者檢查 response.status_code 是否和你的期望相同
6、保存一個二進制文件
二進制內(nèi)容為response.content
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)
7、添加heads信息
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)
8、使用代理
同添加headers方法,代理參數(shù)也要是一個dict
這里使用requests庫爬取了IP代理網(wǎng)站的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.kuaidaili.com/free/'
get_ipport(get_html(url))
9、基本POST請求
import requests
data = {'name':'tom','age':'22'}
response = requests.post('http://httpbin.org/post', data=data)
10、獲取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)
11、會話維持
import requests
session = requests.Session()
session.get('http://httpbin.org/cookies/set/number/12345')
response = session.get('http://httpbin.org/cookies')
print(response.text)
11、證書驗證設置
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)
12、超時異常捕獲
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)
13、異常處理
在你不確定會發(fā)生什么錯誤時,盡量使用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')
總結(jié)
到此這篇關于Python爬蟲之requests庫基本介紹的文章就介紹到這了,更多相關Python requests庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python計算階乘和的方法(1!+2!+3!+...+n!)
今天小編就為大家分享一篇python計算階乘和的方法(1!+2!+3!+...+n!),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02
Django admin實現(xiàn)TextField字段changelist頁面換行、空格正常顯示
本文主要介紹了Django admin實現(xiàn)TextField字段changelist頁面換行、空格正常顯示,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01
Django中更改默認數(shù)據(jù)庫為mysql的方法示例
這篇文章主要介紹了Django中更改默認數(shù)據(jù)庫為mysql的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-12-12

