python+request登陸https網站(設置proxy+SSL證書)

1、因公司需要通過代理連接外網,故這裏需要增加proxies參數 ,參考:https://blog.csdn.net/wdlnancy/article/details/87007000

2、2.1 忽略SSL證書方法

因登陸的是https網站,需要使用SSL證書,但若無證書進行連接的話,可增加verify=False方法忽略證書驗證,但這樣會出現如下告警:

D:\Python35\lib\site-packages\urllib3\connectionpool.py:847: 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)

故在代碼上方增加忽略安全告警的代碼:

requests.packages.urllib3.disable_warnings()

2.2 請求中帶上證書地址(以瀏覽器爲客戶端,解釋SSL證書如何工作的參考文檔https://www.wosign.com/FAQ/how_browser_check_SSL.htm

從瀏覽器中獲取瀏覽器的證書地址,然後在請求體中加上證書路徑,使用證書的最大問題是證書在哪兒弄?,經過探索得到解決:通過瀏覽器查看網頁證書,然後另存爲本地某路徑,參考:https://jingyan.baidu.com/article/20095761903725cb0621b44f.html,但注意導出格式要選擇Base64編碼的選項,如保存到本地:

C:/Users/user/Downloads/github3.cer

代碼修改爲:

 r= requests.get(build_uri('user'),auth=('github賬號','密碼'),proxies=proxies,verify="C:/Users/user/Downloads/github3.cer")

則也正常執行

3、因github是需要用戶登陸後才能繼續進行操作的,故必須在get請求中設置auth信息,若不設置,如下方,則會報401錯誤:

# coding=utf-8
__author__ = 'w00*'
import requests
import json
import ssl

#忽略安全警告
requests.packages.urllib3.disable_warnings()
URL = "https://api.github.com"
proxies = {"http":"http://賬號:密碼@proxycn2.huawei.com:8080","https":"http://賬號:密碼@proxycn2.huawei.com:8080"}
context = ssl._create_unverified_context()
def build_uri(endpoint):
    return '/'.join([URL,endpoint]) #主要作用是拼接接口請求地址

def better_output(json_str):
    return json.dumps(json.loads(json_str),indent=4) #採用json裏面提供方法打印出來

def request_method():
    # r = requests.get(build_uri('user'),auth=('wdlnancysw','wdlsw080705'),proxies=proxies)
    # r= requests.get(build_uri('user'),auth=('Github賬號','密碼'),proxies=proxies,verify=False)
    r= requests.get(build_uri('user'),proxies=proxies,verify=False)
    print (r.status_code)
    print (better_output(r.text)) #調用json更好格式輸出

if __name__=='__main__':
    request_method()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章