您的位置:首页 > 编程语言 > Python开发

Python + Selenium自动化测试 -- Python常用方法

2018-01-11 17:03 471 查看
1、路径

os.path.abspath(‘.’) # 返回绝对路径

os.path.realpath(file) #返回真实路径,方法所在文件的路径

os.getcwd() # 获取当前工作目录,也就是在哪个目录下运行这个程序。【os.path.abspath取决于os.getcwd,如果是一个绝对路径,就返回,如果不是绝对路径,根据编码执行getcwd/getcwdu.

然后把path和当前工作路径连接起来.】

三者区别:

先创建两个文件:

E:\SZR\zdh\logtest\test\getpath.py

E:\SZR\zdh\logtest\dir1\dir2\pathtast.py

getpath.py内容如下:

import os

def absPath():
path1 = os.path.abspath('.')
print(path1)

def realPath():
path2 = os.path.realpath(__file__)
print(path2)

def cwdPath():
path3 = os.getcwd()
print(path3)

absPath()
realPath()
cwdPath()


运行结果:



pathtest中导入getpath模块,并将getpath中调用方法代码注释,在pathtest运行那几个方法,代码如下:

from test import getpath

getpath.absPath()
getpath.realPath()
getpath.cwdPath()


运行结果如下:



其他常用方法:

os.path.dirname(path) # 返回文件路径

os.path.join(path1[, path2[, …]]) # 把目录和文件名合成一个路径

更多方法参考:python 文件、目录属性的操作os.path等os模块函数

2、 时间

1) 从1970年到现在的间隔,单位秒

time.time()

2) 格式化时间

time.strftime(“%Y-%m-%d %H:%M:%S”, time.localtime())

格式化时间 %Y %m %d %H %M %S 中间连词符根据自己需要格式设置

print(time.time())  # time.time()从1970年到现在的间隔,单位秒
print(time.localtime())
# 格式化时间 %Y %m %d %H %M %S 中间连词符根据自己需要格式设置
# newTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
dayTime = time.strftime("%Y-%m-%d", time.localtime())
hourTime = time.strftime("%H:%M:%S", time.localtime())
print(dayTime)
print(hourTime)


运行结果如下:



3、字符串切割

1)split()

不写参数时,默认按照空格切割字段,带参数,则按参数去切割

例:获取“结果约5500个”中间的“5500”

str = "结果约5500个"
rightStr = str.split('约')[1]
num = rightStr.split('个')[0]
print(num)


2)利用正则表达式

re.sub()

'''
sub(pattern, repl, string, count=0, flags=0)
pattern: 正则表达式
repl: 用repl替换,可是字符串,函数
如果没有找到匹配 pattern 的串,则返回未被修改的 string
'''
count = re.sub('\D', "", str)
print(count)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息