1. 程式人生 > >python35中使用requests庫爬https協議下的網站

python35中使用requests庫爬https協議下的網站

使用requests庫可以非常簡單地爬https協議下的網站:

import requests
url='https://www.baidu.com/'
r = requests.get(url,verify=False)
r.encoding = 'utf-8'
print(r.text)

而當爬取TLSv1或TLSv1.1網站時,這樣的程式碼就會報錯 於是我們需要使用HTTPAdapter定製requests引數:

#-*- coding:utf-8 -*-
import re
import requests
from requests.adapters import HTTPAdapter
from
requests.packages.urllib3.poolmanager import PoolManager import ssl import os class MyAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize, block=False): self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, block=
block, ssl_version=ssl.PROTOCOL_TLSv1)#這裡定義了ssl協議版本 s = requests.Session() s.mount('https://', MyAdapter()) def downloadImage(netPath,localPath,imageName):#netPath=網路全路徑,localPath=本地資料夾路徑,imageName=圖片檔名 #檢測當前路徑的有效性 if not os.path.isdir(localPath): os.
makedirs(localPath) ok=0 while(ok==0): try: r=s.get(netPath,timeout=10) ok=1 except: print("連線超時") if(r.status_code==200): fp = open(localPath+'\\'+imageName, 'wb') fp.write(r.content) fp.close() return 1 else: return 0

這樣就可以通過定製HTTPAdapter實現爬取TLSv1或TLSv1.1的網站。