--By setting Proxy in the environment variable of OS, it is not necessary to set Proxy individually for multiple packages such as Selenium and Requests. --By implementing the following, the environment variable settings are valid only for the workbook that is executing this code, so there is little impact on others. --Since the ID / password is not fixedly set in the code and is entered every time, there is little security impact even if the source is leaked.
import os
import getpass
class PROXY:
#Proxy list
proxies = {
"office":{Address of proxy server used in the company:port},
"mobile":{Proxy server address used outside the company:port},
}
def __init__(self,prxy=None):
self.conf(prxy=prxy)
def conf(self,prxy=""):
if prxy not in [None,"office","mobile"]:
prxy = input("Proxy(office|mobile|none)")
if prxy in ["office","mobile"]:
name = input("ID:")
password = getpass.getpass("Password")
self.set_proxy(name,password,prxy=prxy)
else:
prxy = None
self.set_proxy(prxy=prxy)
#Proxy ID,Set Proxy in environment variable from password and connection source
def set_proxy(self,uid=None,pwd=None,prxy=None):
#Remove proxy
if prxy == None:
os.environ.pop('HTTP_PROXY', None)
os.environ.pop('HTTPS_PROXY', None)
print("clear Proxy")
#Set proxy
elif prxy in self.proxies.keys():
prx = self.proxies[prxy]
os.environ['HTTP_PROXY']="http://{}:{}@{}".format(uid,pwd,prx)
os.environ['HTTPS_PROXY']="http://{}:{}@{}".format(uid,pwd,prx)
print("Set {} as Proxy".format(prx))
#Remove proxy
else:
os.environ.pop('HTTP_PROXY', None)
os.environ.pop('HTTPS_PROXY', None)
print("clear Proxy")
#Proxy ID,Set Proxy in environment variable from password and connection source
def check_proxy(self):
print('HTTP_PROXY:{}'.format(os.environ.get('HTTP_PROXY', None)))
print('HTTPS_PROXY:{}'.format(os.environ.get('HTTPS_PROXY', None)))
By describing the following, you will be asked to enter your ID and password except for prxy = None. By entering the correct ID and password, proxy settings that are valid only for the book will be set in the environment variables.
#When using Office Proxy
_ = PROXY(prxy="office")
#When using mobile Proxy
_ = PROXY(prxy="mobile")
#When not using Proxy
_ = PROXY(prxy=None)