python獲取https而且寫文件日誌

# -*- coding: utf-8 -*-
import os
import os.path
import shutil
import chardet
import urllib.request
import http.cookiejar
import ssl
import time
import datetime
import codecs
import socket

def get_url_context_https():
        url="https://120.198.253.63:8094/gds/platform/version/GetVersion.mt?osname=Android&type=2"
        #ssl.socket.settimeout(5)
        context = ssl._create_unverified_context()
        #res_two = urllib.request.urlopen(url)
        #code_two = res_two.getcode()
        #html_two = res_two.read().decode('utf-8')
        request=urllib.request.Request(url)
        response=urllib.request.urlopen(url=request,context=context)
        #print('網頁狀態碼:%s' % (code_two))
        #print('網頁內容:'+html_two)
        #print (response.read().decode('utf-8'))
        print ("https 獲取成功")
        return True

def get_url_context_http():
        try:
                url="xxx"
                #ssl.socket.settimeout(5)
                #context = ssl._create_unverified_context()
                response = urllib.request.urlopen(url)
                code_two = response.getcode()
                html_two = response.read().decode('utf-8')
                #request=urllib.request.Request(url)
                #response=urllib.request.urlopen(url=request,context=context)
                #print('網頁狀態碼:%s' % (code_two))
                #print('網頁內容:'+html_two)
                #print (response.read().decode('utf-8'))
                return "http 獲取成功"
        except Exception as err:
                return "http:"+str(err)
        
file_path="E:\\doc\\py\\test\\get_page_log.txt"
cc=""
i=1
while(i<3600):
        fw=open(file_path,"a+",encoding="utf-8")  #r,w,a+ #,"utf-8"
        try:
               cc=""
               cc=cc+"\r\n"+str(datetime.datetime.now())
               print(datetime.datetime.now())
               if(get_url_context_https()):
                       cc=cc+"\r\n"+"網頁獲取成功"
               else:
                       cc=cc+"\r\n"+"網頁獲取失敗" 
        except Exception as err:
                cc=cc+"\r\n"+str(err)
                print(err)
                hcc=get_url_context_http();
                cc=cc+"\r\n"+hcc
                print(hcc)
        finally:
                print(datetime.datetime.now())
                print("================"+str(i)+"================")
                cc=cc+"\r\n"+str(datetime.datetime.now())
                cc=cc+"\r\n"+"================"+str(i)+"================"
                fw.write(cc)
                fw.close()
                i=i+1
                time.sleep(1)        
相關文章
相關標籤/搜索