一.执行js语法
# 删除readonly属性
js = "$('input:eq(0)').removeAttr('readonly')"
# 修改 type 属性
js = """$('input[name="arrival_date"]').attr('type','')"""
# 获取标签属性值
js = """$("#atmt_error002").css("display")"""
# 直接赋值
js = f"""$("#arrival_date").val("{group['japan_entry_time']}")"""
# 删除禁用
execute_script(f'document.getElementById("{ids}").removeAttribute("disabled")')
# 执行
driver.execute_script(js)
二.获取文件路径
path = sys.path[0] # 获取路径
print(path)
# ['C:\\Users\\Administrator\\Desktop\\new_Thailand', 'C:\\Users\\Administrator\\Desktop\\new_Thailand', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\DLLs', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\lib', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36', 'C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python36\\site-packages', 'C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python36\\site-packages\\win32', 'C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python36\\site-packages\\win32\\lib', 'C:\\Users\\Administrator\\AppData\\Roaming\\Python\\Python36\\site-packages\\Pythonwin', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages']
# 获取路径
dirPath = os.path.dirname(inspect.currentframe().f_code.co_filename)
print(dirPath)
# C:/Users/Administrator/Desktop/new_Thailand
# 获取路径下的所有文件名,带绝对路径
b = glob.glob('e:\\visafiles\\112\ec8656937\\hotel_photo\\*')
print(b)
# ['e:\\visafiles\\112\\ec8656937\\hotel_photo\\jpg1555286134_39396998.jpg']
# 获取路径下的所有文件名,不带绝对路径
filenames = os.listdir('e:\\visafiles\\112\ec8656937\\hotel_photo\\')
print(filenames)
# ['jpg1555286134_39396998.jpg']
# 合并路径
local_path='e:\\visafiles\\112\ec8656937\\hotel_photo\\'
name = 'jpg1555286134_39396998.jpg'
local = os.path.join(local_path, name)
print(local)
# e:\\visafiles\\112\\ec8656937\\hotel_photo\\jpg1555286134_39396998.jpg
三.base64与二进制相互转换
import base64
with open(r'C:\Users\Administrator\Desktop\ceshi_img\1.png','rb') as f:
con = f.read() # 读取二进制文件
bs=base64.b64encode(con) # 将二进制转换为base64
print(bs)
with open(r'C:\Users\Administrator\Desktop\ceshi_img\333333.txt','r') as f:
bs = f.read() # 获取base64格式
con = base64.b64decode(a) # 将base64格式转换为二进制格式
with open(r'C:\Users\Administrator\Desktop\ceshi_img\2.jpg','wb') as f:
f.write(con) #将二进制格式写成图片
四.随机字符串
# string.ascii_letters 所有大写和小写字母
# 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
# string.digits 0-9 数字 '0123456789'
# random.sample 随机16位字符串
# join 拼接
ram = ''.join(random.sample(string.ascii_letters + string.digits, 16))
print(ram) # f1SDsZm4Mw90Wzjn
五.os常用
import shutil
# 判断返回的是否是文件夹/目录
if os.path.isdir(self.local_path):
# 用于递归删除目录/文件夹 == os.removedirs()
shutil.rmtree(self.local_path)
# 删除保存本地的图片
def delect_image():
image_list = ['huzhao', 'zhaopian', 'file_56', 'file_66', 'file_67', 'file_69']
path = sys.path[0]
for i in image_list:
try:
os.remove(path+'/image/{}.jpg'.format(i))
except Exception as f:
print('no such file:{}'.format(path+'/image/{}.jpg'.format(i)))
# 检查目录是否存在,不存在就创建目录
if not os.path.exists(local_path):
os.makedirs(local_path) #逐级创建
os.mkdir(self.download_path) # 创建最后一个
# 获取当前路径,路径拼接
download_dir = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'pdf')
# 改名字
os.rename(oldname, newname)
# 清屏
os.system("cls")
# 逐级创建目录
os.makedirs('d\a\b\c\d')
# 创建最后一级目录
os.mkdir('d\a\b\c\d')
download_path = 'C:/Users/Administrator/Desktop/evus\\files'
for root, dirs, files in os.walk(download_path):
root 所指的是当前正在遍历的这个文件夹的本身的地址
'C:/Users/Administrator/Desktop/evus\\files'
dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录)
<class 'list'>: []
files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)
<class 'list'>: ['01.pdf']
六.sys常用
'''获取文件路径、文件名、后缀名'''
def jwkj_get_filePath_fileName_fileExt(filename):
(filepath, tempfilename) = os.path.split(filename)
(shotname, extension) = os.path.splitext(tempfilename)
return filepath, shotname, extension
data1 = sys.argv[1] # 获取命令行传入的参数
data2 = sys.argv[2] # 获取命令行传入的第二个参数
# python中最大的值
sys.maxsize
七. import time
1. 基本方法
获取当前日期:time.time()
获取元组形式的时间戳:time.local(time.time())
格式化日期的函数(基于元组的形式进行格式化):
(1)time.asctime(time.local(time.time()))
(2)time.strftime(format[,t])
将格式字符串转换为时间戳:
time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
延迟执行:time.sleep([secs]),单位为秒
2. 格式化符号
python中时间日期格式化符号:
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
--------------------------------
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身
import time
# 格式化成2019-11-19 10:00:01形式
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
# 格式化成Tue Nov 19 10:00:02 2019形式
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))
# 将格式字符串转换为时间戳
a = "Tue Nov 19 10:00:02 2019" # 1574128802.0
print(time.mktime(time.strptime(a, "%a %b %d %H:%M:%S %Y")))
八. 时间常用方法
# 1 将字符串的时间转换为时间戳
import time
t = "2017-11-24 17:30:00"
#将其转换为时间数组
timeStruct = time.strptime(t, "%Y-%m-%d %H:%M:%S")
#转换为时间戳:
timeStamp = int(time.mktime(timeStruct))
print(timeStamp) # 1511515800
# 2 时间戳转换为指定格式日期
timeStamp = 1511515800
localTime = time.localtime(timeStamp)
strTime = time.strftime("%Y-%m-%d %H:%M:%S", localTime)
print(strTime) # 2017-11-24 17:30:00
# 3 格式切换
把-分割格式2017-11-24 17:30:00 转换为斜杠分割格式: 结果:2017/11/24 17:30:00
import time
t = "2017-11-24 17:30:00"
#先转换为时间数组,然后转换为其他格式
timeStruct = time.strptime(t, "%Y-%m-%d %H:%M:%S")
strTime = time.strftime("%Y/%m/%d %H:%M:%S", timeStruct)
print(strTime) # 2017/11/24 17:30:00
# 4 获取当前时间并转换为指定日期格式\
import time
#获得当前时间时间戳
now = int(time.time())
#转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
timeStruct = time.localtime(now)
strTime = time.strftime("%Y-%m-%d %H:%M:%S", timeStruct)
print(strTime) # 2017-11-24 18:36:57
# 5 获得三天前的时间的方法
import time
import datetime
#先获得时间数组格式的日期
注:timedelta()的参数有:days,hours,seconds,microseconds
threeDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 3))
#转换为时间戳:
timeStamp = int(time.mktime(threeDayAgo.timetuple()))
#转换为其他字符串格式:
strTime = threeDayAgo.strftime("%Y-%m-%d %H:%M:%S")
print(strTime) # 2017-11-21 18:42:52
# 6 使用datetime模块来获取当前的日期和时间
import datetime
i = datetime.datetime.now()
print ("当前的日期和时间是 %s" % i)
print ("ISO格式的日期和时间是 %s" % i.isoformat() )
print ("当前的年份是 %s" %i.year)
print ("当前的月份是 %s" %i.month)
print ("当前的日期是 %s" %i.day)
print ("dd/mm/yyyy 格式是 %s/%s/%s" % (i.day, i.month, i.year) )
print ("当前小时是 %s" %i.hour)
print ("当前分钟是 %s" %i.minute)
print ("当前秒是 %s" %i.second)
九.计算时间差(天数)
import time
import datetime
#计算两个日期相差天数,自定义函数名,和两个日期的变量名。
def Caltime(date1,date2):
date1=time.strptime(date1,"%Y-%m-%d")
date2=time.strptime(date2,"%Y-%m-%d")
date1=datetime.datetime(date1[0],date1[1],date1[2])
date2=datetime.datetime(date2[0],date2[1],date2[2])
#%Y-%m-%d为日期格式,其中的-可以用其他代替或者不写,但是要统一,同理后面的时分秒也一样;可以只计算日期,不计算时间。
#date1=time.strptime(date1,"%Y-%m-%d %H:%M:%S")
#date2=time.strptime(date2,"%Y-%m-%d %H:%M:%S")
#根据上面需要计算日期还是日期时间,来确定需要几个数组段。下标0表示年,小标1表示月,依次类推...
#date1=datetime.datetime(date1[0],date1[1],date1[2],date1[3],date1[4],date1[5])
#date2=datetime.datetime(date2[0],date2[1],date2[2],date2[3],date2[4],date2[5])
date_c = data2 - data1 # 31 days, 12:30:10
date_c.days # 获取天数 31
date_c.seconds # 获取分钟 # 45010(不算天数的分钟)
#返回两个变量相差的值,就是相差天数
return date2-date1
#判断日期是否为合法输入,年月日的格式需要与上面对应,正确返回True,错误返回False,注意大小写。
def is_date(str):
try:
time.strptime(str,"%Y-%m-%d")
return True
except:
return False
if __name__=='__main__':
#提示信息请根据实际情况更改
print('请输入较早日期(格式例:xxxx-xx-xx):')
while True:
dt1=input()
if is_date(dt1)==True:
break
else:
print('请输入正确的日期!!!请重新输入!!!')
#print(is_date(dt1))
print('\n请输入较晚日期(格式为:xxxx-xx-xx):')
while True:
dt2=input()
if is_date(dt2)==True:
break
else:
print('请输入正确的日期!!!请重新输入!!!')
#将结果保存到当前目录下的t_day.txt,该txt文档会自动创建,名字可自定义。
with open('./t_day.txt','a') as f:
f.write('较早日期为:'+dt1+' 较晚日期为:'+dt2)
f.write('\n两个日期相差 ')
print (Caltime(dt1,dt2),file=f)
f.write('\n')
f.close
十.python计算当前时间的前(后)一分钟,前(后)一小时,前(后)一天
import datetime
print(datetime.datetime.now())
# 2019-11-30 14:49:13.259963
# 格式化时间
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
# 2019-11-30 14:49:13
# 加(减)一天
print((datetime.datetime.now()+datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S"))
# 2019-12-01 14:49:13
print((datetime.datetime.now()-datetime.timedelta(days=1)).strftime("%Y-%m-%d %H:%M:%S"))
# 2019-11-29 14:49:13
# 加(减)一小时
print((datetime.datetime.now()+datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S"))
# 2019-11-30 15:49:13
print((datetime.datetime.now()-datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S"))
# 2019-11-30 13:49:13
# 加(减)一分钟
print((datetime.datetime.now()+datetime.timedelta(minutes=1)).strftime("%Y-%m-%d %H:%M:%S"))
# 2019-11-30 14:50:13
print((datetime.datetime.now()-datetime.timedelta(minutes=1)).strftime("%Y-%m-%d %H:%M:%S"))
# 2019-11-30 14:48:13
十一.根据今天和出生日期计算年龄
import datetime
import re
from datetime import date
def calculate_age(born_date):
born_date= re.sub("-","/",born_date)
born_date= datetime.datetime.strptime(born_date,"%Y/%m/%d") if len(born_date.split('/')[0])>2 else datetime.datetime.strptime(born_date,"%d/%m/%Y")
today = date.today()
return today.year - born_date.year - ((today.month, today.day) < (born_date.month, born_date.day))
print(calculate_age("2002-02-01"))